我一直在摸索 C# 编译器的“继承实例化泛型类”的局限性。
无论如何,这是我的测试用例:
class Program
{
static void Main(string[] args)
{
var x = new InClass();
Console.WriteLine(x.Test(10)); //prints foo
Console.ReadLine();
}
}
class BaseClass<Foo, Bar>
{
public virtual Foo Test(Bar b)
{
return default(Foo);
}
public virtual string Test(int b)
{
return "foo"; ;
}
}
class InClass : BaseClass<string, int>
{
/*public override string Test(int b)
{
return "bar";
}*/
}
我认为 InClass 的这个声明会引发编译器错误,因为它使 Test
不明确。它还使非通用 Test
无法在 InClass
中调用。请注意,我在 InClass
中也注释掉了一些代码。如果我取消注释该代码,我会收到编译器错误。
C# 规范中是否提到了这种行为,或者这是闻所未闻的边缘情况?
最佳答案
I would think that this declaration of InClass would throw a compiler error, as it makes Test ambiguous.
没有。规范在 7.5.3.6 节中明确指出了这种事情:
While signatures as declared must be unique, it is possible that substitution of type arguments might result in identical signatures. In such cases, the tie-breaking rules of overload resolution above will pick the most specific member.
The following examples show overloads that are valid and invalid according to this rule.
(显然,示例如下。)
所以语言设计者已经考虑过了,但大概替代方案会更糟。 (例如,即使您不想调用 Test
,也无法创建诸如 InClass
的类,这会很烦人。)
关于c# - 这种对泛型的滥用如何不模棱两可/在编译器中触发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12099380/