如何在 C# 中调用泛型重载方法

How to call generic overloaded method in C#

不太熟悉 C# 和泛型,所以我可能遗漏了一些明显的东西,但是:

鉴于:

public interface IA { }

public interface IB
{  void DoIt( IA x );
}

public class Foo<T> : IB where T : IA
{
    public void DoIt( IA x )
    {  DoIt(x); // Want to call DoIt( T y ) here
    }

    void DoIt( T y )
    {  // Implementation
    }
}

1)方法void DoIt(T y)为什么不满足接口IB要求的DoIt方法实现?

2) 如何从 DoIt( IA x ) 中调用 DoIt(T y)

1) 因为任何 T IA (这是从约束给出的),但不是每个 IA T:

class A : IA {}
class B : IA {}

var foo_b = new Foo<B>();
var a = new A();

// from the point of IB.DoIt(IA), this is legal;
// from the point of Foo<B>.DoIt(B y), passed argument is not B
foo_b.DoIt(a);

2) 如果你确定 xT,那么使用 cast:

public void DoIt( IA x )
{  
    DoIt((T)x);
}

如果x可以是任何东西,DoIt(T)可以是可选的,使用as:

public void DoIt( IA x )
{  
    DoIt(x as T);
}

void DoIt( T y )
{
    if (y == null)
        return;

    // do it
}

否则,您可以抛出异常或考虑其他方法,具体取决于特定用例。