不太熟悉 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) 如果您确定 x
是 T
,则使用强制转换:
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/