【发布时间】:2018-08-26 08:27:31
【问题描述】:
除非我将GetCount 参数类型从ICollection 更改为dynamic,否则下面的代码工作得很好——它会抛出RuntimrBinderException 为什么在运行时Count 属性不可用?
static void Main(string[] args)
{
var list = new int[] { 1, 2, 3 };
var x = GetCount(list);
Console.WriteLine(x);
}
private static int GetCount(ICollection array) /*changing array type to dynamic fails at runtime*/
{
return array.Count;
}
【问题讨论】:
-
Coz Array 没有 Count 属性。数组具有 Length 属性。试试
array.Length和dynamic -
@ChetanRanpariya :
ICollection -
是的.. 因为 ICollection 有 Count 属性。当您使用动态时,Array 不会转换为 ICollection,编译器将尝试使用特定于传递的类型的属性。并且 Array 没有 Count 属性。 stackoverflow.com/questions/4769971/…
-
Array 通过显式接口实现实现 ICollection.Count 属性,这就是 Count 属性不能直接在 Array 上使用的原因。
标签: c# dynamic dynamic-language-runtime