c# merge objects

安稳与你 提交于 2020-01-15 03:35:11

问题


    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 will have this values

user2.Name will be userName user2.cars will hold the Mazda and the Bmw

thanks !


回答1:


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);



回答2:


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;
     }
 }


来源:https://stackoverflow.com/questions/7504280/c-sharp-merge-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!