我希望能够在 C# 基类中有一个方法,可在几个派生类的对象上调用,返回对象本身,并让 CLR 知道对象的真正类型 - 即,适当的派生类型。 有人可以建议一种方法吗?当然,除了 C# 没有的返回类型协变之外。
类似这样,除了 Method()
的返回类型应该是派生类的类型,而不是基类:
public abstract class Base {
public Base Method() { return this; }
}
public class Derived1: Base { ... }
public class Derived2: Base { ... }
public class Main {
public static int Main() {
Derived1 d1 = new Derived1();
Derived1 x = d1.Method();
Derived2 d2 = new Derived2();
Derived2 y = d2.Method();
}
}
我只能想到两种方法来完成这项工作,而且我都不喜欢其中任何一种:
将 Method() 的结果转换为预期类型(例如,
Derived1 x = (Derived) d1.Method();
)。但是转换是魔鬼的工具,此外,该方法的目的是返回Derived1
或Derived2
或 ...,而不是Base
.在基类中将
Method()
声明为抽象,并在每个派生类中单独实现它。但这与分解出通用方法的想法完全背道而驰。除了返回类型外,Method()
在每种情况下都是相同的。
最佳答案
我相信您可以在 C# 4.0 上使用 dynamic
关键字:
public abstract class Base {
public dynamic Method() { return this; }
}
public class Derived1: Base { ... }
public class Derived2: Base { ... }
public class Main {
public static int Main() {
Derived1 d1 = new Derived1();
Derived1 x = d1.Method();
Console.WriteLine(x.GetType()); // outputs Derived1
Derived2 d2 = new Derived2();
Derived2 y = d2.Method();
Console.WriteLine(y.GetType()); // outputs Derived2
}
}
关于c# - 即使在派生类中,基类方法也能返回 this 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7798256/