为什么在具有接口类型约束的泛型方法中显式 C# 接口调用总是调用基实现?
例如,考虑以下代码:
public interface IBase
{
string Method();
}
public interface IDerived : IBase
{
new string Method();
}
public class Foo : IDerived
{
string IBase.Method()
{
return "IBase.Method";
}
string IDerived.Method()
{
return "IDerived.Method";
}
}
static class Program
{
static void Main()
{
IDerived foo = new Foo();
Console.WriteLine(foo.Method());
Console.WriteLine(GenericMethod<IDerived>(foo));
}
private static string GenericMethod<T>(object foo) where T : class, IBase
{
return (foo as T).Method();
}
}
此代码输出以下内容:
IDerived.Method
IBase.Method
而不是人们可能期望的:
IDerived.Method
IDerived.Method
似乎没有办法(没有反射)调用在运行时决定的类型的隐藏的、更派生的显式接口实现。
编辑:为了清楚起见,以下 if 检查在上面的 GenericMethod 调用中计算为 true:
if (typeof(T) == typeof(IDerived))
所以答案不是因为泛型类型约束“where T: class, IBase”,T 总是被视为 IBase。