簡體   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");

我想合並對象,以便user2將使用user1的名稱和汽車

user2將具有此值

user2.Name將為userName user2.cars將保留馬自達和寶馬

謝謝 !

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

您可以將其作為方法添加到類本身上:

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

這將使您可以編寫如下內容:

user2.Merge(user1);

試試這個擴展方法

 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