我可以做这样的事情吗? (过于简单,因为它太复杂了)
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();
}
我有许多继承自基类 (A) 的类(A1、A2、A3 等)
我正在尝试在 A 类中创建上面的 DoPrint() 函数。 可以吗?
我试过了
public static string DoPrint(A a) {
a.Print();
}
但它调用的是 A.Print(),而不是 A3.Print()
编辑:将标题从“将类型作为参数传递?”更改为因为大家都是对的,我可以只使用虚拟(谢谢!)。问题出在别处,与这个问题无关。
最佳答案
public static string DoPrint(A a) {
a.Print();
}
可以工作,但您需要将 Print 声明为虚拟并覆盖它。
abstract class A {
public virtual string Print() {}
public static string DoPrint(A a) {
a.Print();
}
}
class A1: A {
public override string Print() {}
}
class A2: A {
public override string Print() {}
}
class A3: A {
public override string Print() {}
}
class Somewhere
{
A3 a3 = new A3();
A.DoPrint(a3);
}
关于C# - 继承、覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7525395/