10 c#
考虑以下代码:
static void Main(string[] args)
{
var ints=new List<int> {10,11,22};
Something(ints);//Output:Count is:3
Something(new int[10]); //'System.Array' does not contain
// a definition for 'Count'
Console.ReadLine();
}
static void Something(ICollection collection)
{
dynamic dynamic = collection;
Console.WriteLine("Count is:{0}", dynamic.Count);
}
Run Code Online (Sandbox Code Playgroud)
通过List时,一切都还可以.但是当传递数组并转换为动态我得到这个错误:'System.Array' does not contain a definition for 'Count'.
我知道我的解决方案是什么,但我想知道为什么编译器有这种行为?
Ste*_*ler 15
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);
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以理解为什么dynamic.Count试图调用System.Array.Count.但是,当Array实现具有Count方法的System.Collections.ICollection时,仍然不清楚为什么没有定义Array.Count.实际上,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);
Run Code Online (Sandbox Code Playgroud)