简体   繁体   English

如何在C#中将对象添加到没有引用的对象列表中?

[英]How to Add an object to a list of objects without a reference in C#?

I have a created a custom type in C# called InfInt . 我在C#中创建了一个名为InfInt的自定义类型。 Each InfInt object has its own list of ints declared as follows: 每个InfInt对象都有自己的int列表,声明如下:

public List<int> Numbers = new List<int>();

Then, elsewhere in the program, I have a loop where a temporary InfInt object is needed. 然后,在程序的其他地方,我有一个循环,其中需要一个临时的InfInt对象。 At the end of the loop, when temporary InfInt has been filled with information, I want to add this object to a list of InfInt objects which is declared like this: var ListOfLists = new List<InfInt>(); 在循环的最后,当临时InfInt中已充满信息时,我想将此对象添加到这样声明的InfInt对象列表中: var ListOfLists = new List<InfInt>(); . The following code adds the temporary InfInt object to ListOfLists list of InfInt objects: 下面的代码将临时InfInt对象ListOfLists列表InfInt对象:

ListOfLists.Add(Temp);

Then, right when a new iteration should start, I obviously need to clear the data in the temporary InfInt object. 然后, InfInt在应该开始新的迭代时,我显然需要清除临时InfInt对象中的数据。 I use the following code for this: 我为此使用以下代码:

Temp.Numbers.Clear();

Now comes the problem. 现在出现了问题。 When I clear the Temp 's data, it is cleared in ListOfLists too... How should I fix this? 当我清除Temp的数据时,它也将在ListOfLists清除。如何解决此问题?

Instead of clearing your Temp using 而不是清除您的临时使用

Temp.Numbers.Clear();

You should make a new Temp object 您应该创建一个新的Temp对象

Temp = new InfInt();

InfInt is a reference type which means that temporary InfInt variable is pointing to an object. InfInt是一种引用类型,这意味着临时InfInt变量指向一个对象。 When you add it to the list and then clear it, the content of this instance is cleared. 当您将其添加到列表中然后清除它时,该实例的内容将被清除。

In your loop, create a new instance of InfInt instead of re-using that temporary InfInt . 在循环中,创建一个新的InfInt实例,而不是重新使用该临时InfInt

Here is a MSDN document that describes the difference between Reference Type and Value Type. 这是一个MSDN文档 ,它描述了引用类型和值类型之间的区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM