gpt4 book ai didi

c# - 方法签名中的 ICollection[]

转载 作者:太空宇宙 更新时间:2023-11-03 17:53:02 26 4
gpt4 key购买 nike

我有以下代码。为什么它总是采用“take(ICollection a)”方法?我认为它自己的对象应该是 LinkedList 或 HashSet,所以它应该调用另外两个 take 方法。

class Program
{
static void Main(string[] args)
{
Program p = new Program();

ICollection<String>[] ary = { new LinkedList<String>(), new HashSet<String>() };

foreach (ICollection<String> a in ary)
{
p.take(a);
}

for (int i = 0; i < ary.Length; i++)
{
p.take(ary[i]);
}
}


public void take(HashSet<String> a)
{ }

public void take(LinkedList<String> a)
{}

public void take(ICollection<string> a)
{ }
}

最佳答案

方法分派(dispatch)是基于变量类型完成的,而不是运行时类型。这在 C# 语言规范 7.5.3(重载解决方案)中有详细介绍 - 在整个部分中都没有建议使用变量的运行时类型。调度由编译器根据“参数表达式”处理:

Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, MP is defined to be a better function member than MQ if

• for each argument, the implicit conversion from EX to QX is not better than the implicit conversion from EX to PX, and

• for at least one argument, the conversion from EX to PX is better than the conversion from EX to QX.


如果你想让它动态调度,你可以通过 dynamic :
 foreach (ICollection<String> a in ary)
{
dynamic o = a;
p.take(o);
}
或者,更短的形式:
 foreach (dynamic a in ary)
{
p.take(a);
}

关于c# - 方法签名中的 ICollection[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18641237/

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