gpt4 book ai didi

c# - 获取在 C# 中转换为动态的数组的计数

转载 作者:可可西里 更新时间:2023-11-01 09:01:11 27 4
gpt4 key购买 nike

考虑这段代码:

  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);
}

当传递一个列表时,一切正常。但是当传递数组并转换为动态时,我得到这个错误:'System.Array' does not contain a definition for 'Count'

我知道我的解决方案是什么,但我想知道为什么编译器会有这种行为?

最佳答案

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.Count 的使用者无权访问 Count 属性,除非将 Array 显式转换为 ICollection。 Array.Count 是使用称为 explicit interface implementation 的模式实现的其中 Array.Count 是为 ICollection 显式实现的。并且您只能通过将变量转换为具有此模式的 ICollection 来访问计数方法。这反射(reflect)在 docs for Array 中。 .查找“显式接口(interface)实现”部分。

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);

关于c# - 获取在 C# 中转换为动态的数组的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19473996/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com