C # i generics - dlaczego metoda w klasie bazowej nazywa się zamiast nowej metody w klasie pochodnej?
Jeśli ogólny argument typu (klasy wywołującej lub wywołującej) jest ograniczonywhere T : Base
nowa metoda w T == Derived nie jest wywoływana, zamiast tego wywoływana jest metoda w Base.
Dlaczego typ T jest ignorowany dla wywołania metody, chociaż powinien być znany przed czasem wykonywania?
Aktualizacja: ALE, gdy ograniczenie używa interfejsu takiego jakwhere T : IBase
wywoływana jest metoda w klasie Base (nie jest to metoda w interfejsie, co również jest niemożliwe).
Oznacza to, że system jest w stanie wykryć tak daleko typy i wykracza poza ograniczenie typu! Dlaczego więc nie wykracza poza ograniczenie typu w przypadku ograniczenia typowania?
Czy to oznacza, że metoda w klasie Base, która implementuje interfejs, ma ukryte słowo kluczowe zastępcze dla metody?
Kod testowy:
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);
}
}
Wydajność:
0
0
0
0
1
1
1
2