C# inheritance. Derived class from Base class

后端 未结 4 1997
一生所求
一生所求 2020-12-15 06:28

I have a base class

public class A   
{
    public string s1;
    public string s2;
}

I also have a derived class :

public         


        
4条回答
  •  伪装坚强ぢ
    2020-12-15 06:39

    You could create a generic clone method in class A:

         public T Clone() where T : A, new() {
              return new T() { a = this.a, b = this.b};
         }
    

    Or if you want to make the cloning extendable:

         public T Clone() where T : A, new() {
              var result = new T();
              this.CopyTo(result);
              return result;
         }
    
         protected virtual void CopyTo(A other) {
              other.a = this.a;
              other.b = this.b;
         }
    

    You use it like this:

         A  a = new A();
         // do stuff with a
         // Create a B based on A:
         B b = a.Clone();
    

    Please note: in your example, both the new A(), and the MemberwiseClone will create a new object of type A.

    If you do not want to code the copy method yourself, you could look at a tool like AutoMapper.

提交回复
热议问题