具有相同签名成员已经定义了不同类型约束不同类型、定义、成员

2023-09-03 16:42:13 作者:夏雨初晴づ

我曾与超载有这似乎排他性不同的约束方式运行跨越的问题。这是我的例子:

I have run across an issue with overloading methods that have different constraints that seems exclusive. That is my example:

public class A
{
    public void Do<T>() where T : class
    {

    }

    public void Do<T>() where T : struct 
    {

    }
}

这不能编译,出现以下错误会员与已经定义了相同的签名。是否有可能满足这两个条件的同时或它的C#编译器只是限制?

And this does not compile with the following error "Member with the same signature already defined". Is it possible to satisfy both conditions at once or it's just the limitation of the C# compiler?

推荐答案

这不是一种限制的编译器的 - 它的的语言的(并且很可能是一个限制CLR为好;我不知道)

It's not a limitation of the compiler - it's a limitation of the language (and quite possibly the CLR as well; I'm not sure).

从根本上那些冲突重载 - 这就像试图返回类型超载。它不支持。

Fundamentally those are clashing overloads - it's like trying to overload by return type. It's not supported.

它的是的可以声明方法,使得这些调用所有编译成不同的方法调用:

It is possible to declare methods such that these calls all compile to invocations of different methods:

a.Do<int>();
a.Do<string>();
a.Do<int?>();

...但它总是涉及可选的参数和/或参数数组,它的horrible.

另外请注意,虽然你不能用一般的约束超载,你的可以的过载由通用的元数(类型参数的数量):

Also note that although you can't overload by generic constraints, you can overload by the generic "arity" (the number of type parameters):

public void Foo() {}
public void Foo<T>() {}
public void Foo<T1, T2>() {}