如果通用类型参数(或者是调用类或方法调用的)与受约束where T : Base
中衍生的T ==新方法不被调用,而不是基地方法被调用。
为什么T型忽略方法调用,即使它应该运行时间之前知道?
更新 :但是,当该约束,使用等的接口where T : IBase
在基类中的方法被调用(未在接口中的方法,这也是不可能的)。
因此,这意味着该系统实际上是能够远远检测的种类和超越类型约束! 那么为什么没有超越类型约束类类型的约束的情况下?
这是否意味着,在基类中实现接口的方法的方法隐含override关键字?
测试代码:
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