如果泛型类型参数(调用类或调用方法)受到where T : Base
T == Derived 中的新方法的约束,则不会调用 Base 中的方法。
为什么类型 T 被方法调用忽略,即使它应该在运行时之前知道?
更新:但是,当约束使用像where T : IBase
基类中的方法这样的接口时(不是接口中的方法,这也是不可能的)。
这意味着系统实际上能够检测到远远超出类型约束的类型!那么为什么在类类型约束的情况下它不超出类型约束呢?
这是否意味着实现接口的基类中的方法具有该方法的隐式覆盖关键字?
测试代码:
public interface IBase
{
void Method();
}
public class Base : IBase
{
public void Method()
{
}
}
public class Derived : Base
{
public int i = 0;
public new void Method()
{
i++;
}
}
public class Generic<T>
where T : Base
{
public void CallMethod(T obj)
{
obj.Method(); //calls Base.Method()
}
public void CallMethod2<T2>(T2 obj)
where T2 : T
{
obj.Method(); //calls Base.Method()
}
}
public class GenericWithInterfaceConstraint<T>
where T : IBase
{
public void CallMethod(T obj)
{
obj.Method(); //calls Base.Method()
}
public void CallMethod2<T2>(T2 obj)
where T2 : T
{
obj.Method(); //calls Base.Method()
}
}
public class NonGeneric
{
public void CallMethod(Derived obj)
{
obj.Method(); //calls Derived.Method()
}
public void CallMethod2<T>(T obj)
where T : Base
{
obj.Method(); //calls Base.Method()
}
public void CallMethod3<T>(T obj)
where T : IBase
{
obj.Method(); //calls Base.Method()
}
}
public class NewMethod
{
unsafe static void Main(string[] args)
{
Generic<Derived> genericObj = new Generic<Derived>();
GenericWithInterfaceConstraint<Derived> genericObj2 = new GenericWithInterfaceConstraint<Derived>();
NonGeneric nonGenericObj = new NonGeneric();
Derived obj = new Derived();
genericObj.CallMethod(obj); //calls Base.Method()
Console.WriteLine(obj.i);
genericObj.CallMethod2(obj); //calls Base.Method()
Console.WriteLine(obj.i);
genericObj2.CallMethod(obj); //calls Base.Method()
Console.WriteLine(obj.i);
genericObj2.CallMethod2(obj); //calls Base.Method()
Console.WriteLine(obj.i);
nonGenericObj.CallMethod(obj); //calls Derived.Method()
Console.WriteLine(obj.i);
nonGenericObj.CallMethod2(obj); //calls Base.Method()
Console.WriteLine(obj.i);
nonGenericObj.CallMethod3(obj); //calls Base.Method()
Console.WriteLine(obj.i);
obj.Method(); //calls Derived.Method()
Console.WriteLine(obj.i);
}
}
输出:
0
0
0
0
1
1
1
2