C#合并对象 [英] c# merge objects

查看:137
本文介绍了C#合并对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类人
    {
        字符串名称
        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);
 


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

 公共类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);

这篇关于C#合并对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆