Something(new int[10]);
static void Something(ICollection collection)
{
//The dynamic keyword tells the compilier to look at the underlying information
//at runtime to determine the variable's type. In this case, the underlying
//information suggests that dynamic should be an array because the variable you
//passed in is an array. Then it'll try to call Array.Count.
dynamic dynamic = collection;
Console.WriteLine("Count is:{0}", dynamic.Count);
//If you check the type of variable, you'll see that it is an ICollection because
//that's what type this function expected. Then this code will try to call
//ICollection.Count
var variable = collection;
Console.WriteLine("Count is:{0}", variable.Count);
}
现在我们可以理解为什么 dynamic.Count 试图调用 System.Array.Count。但是,仍然不清楚为什么 Array.Count 在 Array 实现具有 Count 方法的 System.Collections.ICollection 时未定义。Array 实际上确实正确地实现了 ICollection,并且它确实有一个 Count 方法。但是,如果未将 Array 显式转换为 ICollection,则 Array.Count 的使用者无权访问 Count 属性。Array.Count 是用一种称为显式接口实现的模式实现的,其中 Array.Count 是为 ICollection 显式实现的。您只能通过使用此模式将变量转换为 ICollection 来访问 count 方法。这反映在Array 的文档中. 查找“显式接口实现”部分。
var myArray = new int[10];
//Won't work because Array.Count is implemented with explicit interface implementation
//where the interface is ICollection
Console.Write(myArray.Count);
//Will work because we've casted the Array to an ICollection
Console.Write(((ICollection)myArray).Count);