简体   繁体   English

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

[英]How to call generic overloaded method in C#

Not very familiar with C# and generics so I may be missing something obvious, but: 对C#和泛型不是很熟悉,因此我可能会缺少一些明显的东西,但是:

Given: 鉴于:

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) Why doesn't the method void DoIt(T y) satisfy the DoIt method implementation required by interface IB ? 1)为什么方法void DoIt(T y)满足接口IB要求的DoIt方法实现?

2) How can I call DoIt(T y) from within DoIt( IA x ) ? 2)如何从DoIt( IA x )内调用DoIt(T y) DoIt( IA x )

1) Because any T is IA (this is given from contraint), but not every IA is T : 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) If you are sure, that x is T , then use cast: 2)如果确定xT ,则使用强制转换:

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

if x can be anything, and DoIt(T) can be optional, use as : 如果x可以是任意值,并且DoIt(T)是可选的,请as

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

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

    // do it
}

Otherwise you can throw exception or consider another approach, depending on particular use case. 否则,您可以根据特定的用例引发异常或考虑其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM