C#合并对象对象

2023-09-06 05:40:07 作者:杯酒困英雄

 类人
    {
        字符串名称
        INT YESNO
        INT变化
        名单<汽车> Personcars;
        房子Personhouses
    }

个人用户1 =新的Person()
个人用户2 =新的Person()

user1.Name =username的
user2.Name =;

user2.cars [0] =新车(马自达);
user1.cars [0] =新车(宝马);
 

我要合并的对象,使用户2会取的名字和车从用户1

用户2将有这样的价值观

user2.Name会的userName user2.cars将持有的马自达和宝马

谢谢!

解决方案

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

C .net的起源

您可以添加为该类本身的方法:

 公共类Person
{
    名单<汽车> _personcars;

    公共字符串名称{;组; }
    //这到底是YESNO INT?如果是1或0,只使用一个bool
    公众诠释YESNO {获得;组; }
    公众诠释更改{获得;组; }
    公开名单<汽车> Personcars
    {
        得到
        {
            返回_personcars? (_personCars =新名单,其中,汽车>());
        }
        集合{_personcars =价值; }
    }
    公房Personhouses {获得;组; }

    公共无效合并(人人)
    {
        NAME = person.Name;
        Personcars.AddRange(person.Personcars);
    }
}
 

这将使你写的是这样的:

  user2.Merge(用户1);
 

    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 !

解决方案

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

 
精彩推荐
图片推荐