C# - Making all derived classes call the base class constructor

前端 未结 4 770
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 17:15

I have a base class Character which has several classes deriving from it. The base class has various fields and methods.

All of my derived classes use the same base

4条回答
  •  孤城傲影
    2020-11-27 18:12

    I had the same problem, and I solved it by replacing my constructor with a factory method like this:

    A is the parent class.

    public static T getChild(int number) where T:A, new()
    {
        T child = new T();
        T._number = number;
        return child;
    
    }
    

    You can create a Child class with

    Child b = A.getChild(2);

提交回复
热议问题