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

标签 c# generics overloading

不太熟悉 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)不满足接口(interface)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,则使用强制转换:

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
}

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

关于c# - 如何在C#中调用泛型重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35909172/

相关文章:

c++ - 重载函数声明的顺序在 C++ 中重要吗?

c# - 通过Selenium点击Captcha总是引发图片验证

c# - 如何在返回的类上实现接口(interface)并保留其数据?

c# - 如何异步读取 XML 文件?

c# - 修改获取集合;枚举操作可能无法执行。异常(exception)

c# - 如何将值传递给 C# 泛型?

delphi - 具有接口(interface)类型约束的泛型类型的 RTTI

C# 通用协变错误

c# - 选择不同的重载方法,具体取决于使用空参数调用它的位置

c++ - 重载函数调用问题