【发布时间】:2011-12-09 12:58:33
【问题描述】:
我希望能够在 C# 基类中有一个方法,可在多个派生类的对象上调用,返回对象本身,并让 CLR 知道对象的真正类型 - ie ,适当的派生类型。 有人可以建议一种方法吗? 当然,除了返回类型协方差之外,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# derived-class