简体   繁体   English

C#合并对象

[英]c# merge objects

    Class Person
    {
        string Name
        int yesno
        int Change
        List<Cars> Personcars;
        houses Personhouses
    }

Person user1 = new Person()
Person user2 = new Person()

user1.Name = "userName"
user2.Name ="";

user2.cars[0] = new car("Mazda");
user1.cars[0] = new car("BMW");

i want to merge the objects so that user2 will take the name and the car from user1 我想合并对象,以便user2将使用user1的名称和汽车

user2 will have this values user2将具有此值

user2.Name will be userName user2.cars will hold the Mazda and the Bmw user2.Name将为userName user2.cars将保留马自达和宝马

thanks ! 谢谢 !

user2.Name = user1.Name;
user2.Personcars.AddRange(user1.Personcars);

You could add this as a method on the class itself: 您可以将其作为方法添加到类本身上:

public class Person
{
    List<Cars> _personcars;

    public string Name { get; set; }
    // what the hell is a yesno int? If it's 1 or 0 then just use a bool
    public int yesno { get; set; }
    public int Change { get; set; }
    public List<Cars> Personcars 
    {
        get
        {
            return _personcars ?? (_personCars = new List<Cars>());
        }
        set { _personcars = value; }
    }
    public Houses Personhouses { get; set; }

    public void Merge(Person person)
    {
        Name = person.Name;
        Personcars.AddRange(person.Personcars);
    }
}

Which will allow you to write something like this: 这将使您可以编写如下内容:

user2.Merge(user1);

Try this extension methods 试试这个扩展方法

 public void Merge(this Person _person, Person source)
 {
     _person.Name = source.Name;
     if(_person.Cars !=null)
     {
        _person.Cars.AddRang(source.Cars);
     }
     else
     {
        _person.Cars = source.Cars;
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM