How to override method with derived return type in C#?

后端 未结 3 506
南旧
南旧 2021-01-25 20:28

I want to override a virtual method with a derived class type. What\'s the current best way to do this? So far I\'ve found two approaches:

  1. Use an abstract<
3条回答
  •  春和景丽
    2021-01-25 21:22

    You could make the base class generic:

    public abstract class Base where TDerived : Base {
      public abstract TDerived Clone();
    }
    
    public class Derived1 : Base {
      public override Derived1 Clone() { ... }
    }
    
    public class Derived2 : Base {
      public override Derived2 Clone() { ... }
    }
    

    However this makes me wonder how useful having a common base class is. Perhaps the Clone implementations of Derived1 and Derived2 don't need to be part of a common interface.

提交回复
热议问题