【发布时间】:2020-05-19 02:09:01
【问题描述】:
我有一些代码,它会抛出。我不明白为什么。
string s="asdf";
Console.WriteLine(s[1..3]);
dynamic d="asdf";
Console.WriteLine(d[1..3]); // throws
// RuntimeBinderException: The best overloaded method match for 'string.this[int]' has some invalid arguments
有一些静态解析的编译器魔法吗?生成的 IL 表明了这一点。
callvirt System.String.Substring
有没有办法在动态声明的表达式上使用范围索引?
【问题讨论】:
-
我猜
dynamic不是Countable- docs.microsoft.com/en-us/dotnet/csharp/language-reference/…。 -
"一个类型是 Countable 如果它有一个名为
Length或Count且具有可访问 getter 和返回类型的属性987654328@"。我不明白为什么它不符合条件。