c# - 这种对泛型的滥用如何不模棱两可/在编译器中触发错误

标签 c# .net generics compiler-errors specifications

我一直在摸索 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/

相关文章:

c# - 从 C# 调用时将记录选项返回为 null

c# - 将 UIImage 转换为流

c# - 动态编译代码时出现IOException

C# HttpWebRequest 验证/指定使用的密码

java - 我可以提供使用泛型类型的方法,其中泛型类型始终是类吗?

generics - Kotlin 泛型更改返回类型

c# - 如何使用C#下载网页

c# - 当我使用 Control-C 中断 C# 控制台应用程序时会发生什么?

generics - 符合两种协议(protocol)的 Swift 泛型类型

c# - 在 C# 中将通用集合转换为 JSON