有没有办法通过类的层次结构分配属性?

时间:2015-11-03 19:47:50

标签: c# override

请参阅以下课程层次结构:

Person [age, country, hair color, eyes color..]
   Adult [job, car..]
      Man [favorite beer..]
      Woman [purse..]
   Child [school, favorite toy]
      Boy
      Girl [doll]

这些派生类中的每一个都具有特定属性:例如,成年人可能有工作但孩子没有工作。一个女孩可能有一个最喜欢的娃娃和一个学校的名字。一个男孩也有学校的名字,但他没有任何喜欢的娃娃。

我想实现一个克隆Boy的方法(使用完全相同的属性返回Boy个对象)。我没有返回Boy并手动设置从ChildPerson继承的所有属性,而是希望避免这种情况。

注意:ChildAdultPerson是抽象类。

注意2:所有这些人都有复杂的参考文献,我不想复制,在某些情况下我只想复制参考文献的ID,但这应该手动完成,所以我需要一些控制克隆的对象。

我已经想到Person中的虚拟方法在每个子类中被覆盖,但由于Person无法实例化,我不确定如何实现此行为。< / p>

4 个答案:

答案 0 :(得分:1)

拿3 ...

解决方案1:

我首选的方法是使用ICopyTo。我认为它比其他任何东西更可取,因为它强制要有一个适当类型的对象来复制到。它还可以同时进行克隆和复制。更易于维护。

还使用界面帮助做正确的事情。别忘了打电话给base.CopyTo ...

另外,我们可以说CopyTo是Fluent interface

的一部分
public interface ICopyTo<T>
{
    T CopyTo(T target);
}

public abstract class Person : ICopyTo<Person>, ICloneable
{
    public Person CopyTo(Person person)
    {
        person.Age = Age;
        person.Country = Country;
        return person;
    }

    public abstract object Clone();

    public int Age { get; set; }
    public string Country { get; set; }
}

public abstract class Adult : Person, ICopyTo<Adult>, ICloneable
{
    public Adult CopyTo(Adult adult)
    {
        base.CopyTo(this);
        adult.Car = Car;
        return adult;
    }

    public string Car { get; set; }
}

public class Man : Adult, ICopyTo<Man>,  ICloneable
{
    public Man CopyTo(Man man = null)
    {
        if (man == null)
        {
            man = new Man();
        }
        base.CopyTo(this);
        man.Beer = Beer;

        return man;
    }


    public string Beer { get; set; }

    public override object Clone()
    {
        return CopyTo();
    }
}

public class Woman : Adult, ICopyTo<Woman>, ICloneable
{
    public Woman CopyTo(Woman woman = null)
    {
        if (woman == null)
        {
            woman = new Woman();
        }
        base.CopyTo(this);
        woman.Purse = Purse;
        return woman;
    }

    public string Purse { get; set; }

    public override object Clone()
    {
        return CopyTo();
    }
}

public class Test
{
    public static void Go()
    {
        Man man1 = new Man() {Age = 10, Beer = "Bud", Country = "Canada"};
        Man man2 = new Man();
        man1.CopyTo(man2); // Real copy

        Woman woman1 = new Woman() {Age = 32, Country = "USA", Purse = "Anything"};
        Woman woman2 = woman1.CopyTo(); // Cloning

        List<Person> adults = new List<Person>();
        adults.Add(man1);
        adults.Add(man2);
        adults.Add(woman2);

        Person person0 = adults[0].Clone() as Person;
        Person person1 = adults[1].Clone() as Person;
        Person person2 = adults[2].Clone() as Person;
    }
}

解决方案2 :(接近解决方案1但仅在基类时使用ICloneable)

public interface ICopyTo<T>
{
    T CopyTo(T target);
}

public abstract class Person : ICopyTo<Person>, ICloneable
{
    public virtual Person CopyTo(Person person)
    {
        if (person == null)
        {
            throw new ArgumentNullException("person can't be null");
        }

        person.Age = Age;
        person.Country = Country;
        return person;
    }

    public object Clone()
    {
        return CopyTo(null);
    }

    public int Age { get; set; }
    public string Country { get; set; }
}

public abstract class Adult : Person, ICopyTo<Adult>, ICloneable
{
    public Adult CopyTo(Adult adult)
    {
        if (adult == null)
        {
            throw new ArgumentNullException("adult can't be null");
        }

        base.CopyTo(this);
        adult.Car = Car;
        return adult;
    }

    public override Person CopyTo(Person person)
    {
        return CopyTo(person as Adult);
    }

    public string Car { get; set; }
}

public class Man : Adult, ICopyTo<Man>
{
    public Man CopyTo(Man man = null)
    {
        if (man == null)
        {
            man = new Man();
        }
        base.CopyTo(this);
        man.Beer = Beer;

        return man;
    }

    public override Person CopyTo(Person person)
    {
        return CopyTo(person as Man);
    }

    public string Beer { get; set; }
}

public class Woman : Adult, ICopyTo<Woman>
{
    public Woman CopyTo(Woman woman = null)
    {
        if (woman == null)
        {
            woman = new Woman();
        }
        base.CopyTo(this);
        woman.Purse = Purse;
        return woman;
    }

    public override Person CopyTo(Person person)
    {
        return CopyTo(person as Woman);
    }

    public string Purse { get; set; }
}

public class Test
{
    public static void Go()
    {
        Man man1 = new Man() {Age = 10, Beer = "Bud", Country = "Canada"};
        Man man2 = new Man();
        man1.CopyTo(man2); // Real copy

        Woman woman1 = new Woman() {Age = 32, Country = "USA", Purse = "Anything"};
        Woman woman2 = woman1.CopyTo(); // Cloning

        List<Person> adults = new List<Person>();
        adults.Add(man1);
        adults.Add(man2);
        adults.Add(woman2);

        Person person0 = adults[0].Clone() as Person;
        Person person1 = adults[1].Clone() as Person;
        Person person2 = adults[2].Clone() as Person;
    }
}

解决方案3:

public static T Clone<T>(T source)
{
    if (!typeof(T).IsSerializable)
    {
        throw new ArgumentException("The type must be serializable.", "source");
    }

    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    using (stream)
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}

答案 1 :(得分:0)

MemberwiseClone()方法可能是您正在寻找的方法:https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

请注意,您需要手动克隆类中任何引用类型的成员,因为上面的函数只会克隆它们的引用,并且生成的Boy clone的成员将引用相同的实例作为这些成员的原件。

如果您的大多数或所有成员都是参考类型,ICloneable是一个更强大的解决方案:https://msdn.microsoft.com/en-us/library/system.icloneable(v=vs.110).aspx

答案 2 :(得分:0)

如果没有沿着路径浅/深度克隆(正如Marco指出的那样),您可以使用自己的Clone函数实现此目的。

class Person
{
   public Person(Person rhs) // cctor
   {
       Age = rhs.Age;
   }

   public int Age { get; set; }

   public abstract Person Clone();
}


   public class Adult : Person
   {
       public Adult(Adult rhs) : base(rhs)
       {
           JobType = rhs.JobType;
       }

       public JobType Job { get; set; }

       public override Person Clone() { return new Adult(this); }
   }

答案 3 :(得分:0)

你可以在基类上使用simple,如果你想在上层中重写,可以使用virtual。

public abstract class Person : ICloneable {
             public virtual object Clone() {
              //all upper classes is a Person object
              person = (Person)Activator.CreateInstance(this.GetType());
                    person.job = this.job; 
                    // ect more properties Lazy or Deep clone
                    person.blah = this.blah;
                    return person;
                }
           }

public abstract class Adult : Person {
      override object Clone() {
                    Adult adult =  (Adult) base.Clone();
                    adult.job = this.job;
                }
          }