c# - 即使在派生类中,基类方法也能返回 this 吗?

标签 c# derived-class

我希望能够在 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();
    }
}

我只能想到两种方法来完成这项工作,而且我都不喜欢其中任何一种:

  1. 将 Method() 的结果转换为预期类型(例如Derived1 x = (Derived) d1.Method();)。但是转换是魔鬼的工具,此外,该方法的目的是返回 Derived1Derived2 或 ...,而不是 Base.

  2. 在基类中将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/

相关文章:

c# - 如何访问枚举 OracleDbType?

c++ - 从派生类访问基类的 protected 数据成员

c++ - 从派生类创建复制构造函数和赋值运算符

c++ - 有没有更好的方法来编写这个 C++ 代码

c++ - 我可以在基类中调用派生类的函数吗?

c# - 将字符串转换为 DateTime 格式问题 C#

c# - 封一个类

c# - 如何获取页面源并使用Watin进行搜索

c# - "Operation could destablize the runtime"和具有值类型的 DynamicMethod

c++ - 使用带有参数的 boost::function 来共享指向派生类的指针