C# 多态性不适用于C中泛型类的调用#

C# 多态性不适用于C中泛型类的调用#,c#,class,generics,interface,polymorphism,C#,Class,Generics,Interface,Polymorphism,在以下情况下,多态性似乎无法正常工作 我有以下定义: interface BaseInterface{} interface NewInterface:BaseInterface{} class NewClass:NewInterface{} class GenericClass<T> where T:BaseInterface { public string WhoIAm(T anObject) { return TestPolymorphism.

在以下情况下,多态性似乎无法正常工作 我有以下定义:

interface BaseInterface{}
interface NewInterface:BaseInterface{}
class NewClass:NewInterface{}

class GenericClass<T> where T:BaseInterface
{
    public string WhoIAm(T anObject)
    {
        return TestPolymorphism.CheckInterface(anObject);
    }
}

class ImplementedClass:GenericClass<NewInterface>{}

class TestPolymorphism
{
    public static string CheckInterface(BaseInterface anInterface)
    {
        return "BaseInterface";
    }

    public static string CheckInterface(NewInterface anInterface)
    {
        return "NewInterface";
    }
}
我有“结果是BaseInterface”

我希望“结果是新接口”作为nc实现基类和NewClass
获得“新课程”的最佳方式是什么


感谢

请记住泛型方法,非虚拟方法调用仍然在泛型本身的编译时解决,而不是在泛型实现的编译时解决

因此:

class GenericClass<T> where T:BaseInterface
{
    public string WhoIAm(T anObject)
    {
        return TestPolymorphism.CheckInterface(anObject);
    }
}
所以你会想如果你把这个叫做:

var s1 = "ello";
var s2 = "Hello";

UberEquals<string>('H' + s1, s2);

在上面,X总是说
BaseInterface
,因为重载是在编译时解决的,而不是在运行时动态解决的。非常类似于泛型,请记住泛型是在实现之前编译的,因此,为了解决重载问题,它只能在任何基类或接口上运行。

没有看到
ImplementedClass
定义。我刚刚添加了ImplementedClass定义,除了使用
dynamic
类型时,C使用编译时绑定。甚至虚拟函数调用也有编译时间限制;它们只是绑定到vtable插槽,而不是绑定到方法的代码。除非使用的是
动态
或反射,否则不应该期望C#中的程序以需要运行时绑定的方式运行。
public static bool UberEquals<T>(T left, T right) where T : class
{
    return left == right;
}
var s1 = "ello";
var s2 = "Hello";

UberEquals<string>('H' + s1, s2);
BaseInterface bi = new ImplementedClass();

var x = TestPolymorphism.CheckInterface(bi);