将对象添加到对象列表而不重复创建对象 [英] Add Objects to the List of Object without creating object repeatedly

查看:81
本文介绍了将对象添加到对象列表而不重复创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想创建一个像下面这样的对象列表,





I'm looking to create a list of object something like below,

List<MenuItem> MyMenuItems = new List<MenuItem>();

private void Form1_Load(object sender, EventArgs e)
{
    MyMenuItems.Add(new MenuItem(1, "Sales"));
    MyMenuItems.Add(new MenuItem(2, "Purchase"));
    MyMenuItems.Add(new MenuItem(3, "Stock"));
    MyMenuItems.Add(new MenuItem(4, "Deliveries"));
    MyMenuItems.Add(new MenuItem(5, "Returns"));

}





其中MyMenuItems是一个具有2个属性Id和Name的对象。 />


在上面的示例中,在向列表添加对象时,我需要每次都创建一个新对象。



无论如何我在那里可以重复使用只创建一次的对象。



上面的对象是一个虚拟对象,我有一个具有10个属性的对象,同时添加它列表中的一些属性可能是null也可能不是null。



我需要处理这种情况,因为在创建多个对象并将其添加到列表时,性能问题即将到来up。



Where MyMenuItems is an object with 2 properties Id and Name.

Here in the above example while adding objects to the list I need to create a new object everytime.

I there anyway where I can reuse the object which is created only once.

The above object is a dummy object, I have an object which has 10 properties and while adding it to the list some properties may or may not be null.

I need to handle this scenario because while creating multiple objects and adding it to list a performance issue is coming up.

推荐答案

您无法重复使用某个对象并将其添加到列表中:

You can't "reuse" an object and add it to a list:
public class MyClass
    {
    public string Name { get; set; }
    public int Number { get; set; }
    public MyClass(string name) { Name = name; }
    }




List<MyClass> list = new List<MyClass>();
MyClass instance = new MyClass("Joe");
instance.Number = 666;
list.Add(instance);
instance.Name = "Mike";
list.Add(instance);
foreach (MyClass mc in list) Console.WriteLine("Name: {0}, Number: {1}", mc.Name, mc.Number);

将输出:

Will output:

Name: Mike, Number: 666
Name: Mike, Number: 666

因为列表存储了对您添加的对象实例的引用,而不是它的副本。 (因此Class实例是一个引用类型 - 你总是传递对象的引用)。



如果你想在列表中添加不同的对象,你必须为您添加的每个实例创建新实例 - 性能问题与否。

because the list stores a reference to the instance of the object you add, not a copy of it. (Hence a Class instance is a Reference Type - you pass around references to the object all the time).

If you want to add different objects to the list, you have to create new instances for each one you add - performance issue or not.


这篇关于将对象添加到对象列表而不重复创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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