Clone derived class from base class method

后端 未结 7 2229
萌比男神i
萌比男神i 2021-02-08 17:09

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.

<
相关标签:
7条回答
  • 2021-02-08 18:12

    I got another idea using the Activator class:

    public class Base
    {
        public virtual object Clone()
        {
            Base copy = (Base)Activator.CreateInstance(this.GetType());
            copy.Id = this.Id;
            return copy;
        }
    
    
        public string Id { get; set; }
    }
    
    public class A : Base
    {
        public override object Clone()
        {
            A copy = (A)base.Clone();
            copy.Name = this.Name;
            return copy;
        }
    
        public string Name { get; set; }
    }
    
    A a = new A();
    A aCopy = (A)a.Clone();
    

    But i would go for the Alexander Simonov answer.

    0 讨论(0)
提交回复
热议问题