Member with the same signature already defined with different type constraints

烈酒焚心 提交于 2019-12-01 04:25:31
Jon Skeet

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

... but it always involves optional parameters and/or parameter arrays, and it's 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>() {}

You cannot overload a method by varing the generic parameter containts. For a valid method overload you have to have different input parameters to the method.

Both methods should have the following name when compiled:

A.Do``1

As the count of generic parameters goes into the name of the method or class.

Not sure what your situation is but you may need to make use of reflection to call those methods:

public class A
{
    public void Do<T>()
    {
        if(typeof(T).IsValueType){
            // nasty reflection to call DoValueType
        }
        else {
            // nasty reflection to call DoReferenceType
        }
    }
    private void DoReferenceType<T>() where T : class {

    }
    private void DoValueType<T>() where T : struct {

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!