我可以这样做吗? (过于简单化了,因为它太复杂)C# - 继承,覆盖
abstract class A {
public string Print() {}
public static string DoPrint(A a, Type T) {
((T)a).Print(); // <-- This should call eg. A3.Print(), not A.Print()
}
}
class A1: A {
public new string Print() {}
}
class A2: A {
}
class A3: A {
public new string Print() {}
}
class Somewhere
{
A3 a3 = new A3();
a3.DoPrint();
}
我有很多类(A1,A2,A3等),其从基类继承(A)
我试图创建上面的A类中的DoPrint()函数。 可以这样做吗?
我想这
public static string DoPrint(A a) {
a.Print();
}
但它调用A.Print(),而不是A3.Print()
编辑: “传递一个类型作为参数” 改了称呼从因为每个人都是对的,我可以使用虚拟(谢谢!)。这个问题在别的地方撒了谎,与这个问题无关。
为什么你在'A1'等''Print'方法声明中指定'new'关键字?如果是关闭编译器警告,请将它们取出并考虑警告给出的建议。 –
你不需要传递类型。只需使Print方法在所有类中都是虚拟的并且可以工作。 –
为什么不让'Print'成为'virtual'方法?这就是'虚拟'的意义所在。 – Jon