我有一个继承自多个派生类的抽象BaseClass。
我想编写一个执行通用工作的通用方法,因此不需要为每个派生类编写该方法。

当前代码-

  public abstract class BaseClass{}


    public class Derived1 : BaseClass{
      public Derived1 CommonWork(){

      /* Common work */
      return objDerived1;
      }

}

 public class Derived2 : BaseClass{
      public Derived2 CommonWork(){

      /* Common work */
      return objDerived2;
      }

}


我想要的方式-

public T CommonWork where T : BaseClass

{
/* Common work */
return T;

}


现在我不知道如何以及在哪里编写此方法。 Coudnt在其他任何地方都可以找到它。
请提出建议。谢谢

最佳答案

你的意思是这样的:

public class CommonWork<T>
  where T: BaseClass,
           new T()// <- probably you'll need it to create instances of T

  public T CommonWork(){
    T result = new T();
    ...

    return T;
  }
}

...

Commonwork<Derived2> common = new Commonwork<Derived2>();

BaseClass result = common.CommonWork();

关于c# - 为派生类编写通用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22754314/

10-10 08:04