![](/img/trans.png)
[英]Access specific properties of an object contained within a List<Object> in C#
[英]C# list within object addressing/access issue
我有一些代码。 我有一堂课:
public class TestClass
{
private string String1 = "";
private List<string> Strings = new List<string>();
public TestClass(string String1, List<string> Strings)
{
this.String1 = String1;
this.Strings = Strings;
} // end constructor.
// Associated get/set methods.
} // end class.
然后,我有(在另一个类中,一些使用此代码的代码):
public TestMethod()
{
List<string> Strings = new List<string>();
List<TestClass> MasterList = new List<TestClass>();
int Counter = 0;
string Name = " ... " // <- updated every time.
while(Condition1)
{
if(Condition2)
{
Strings.Add(Counter.ToString());
}
else
{
MasterList.Add(new TestClass(Name, Strings));
Name = // ... <- name updated here.
Strings.Clear(); // Clear array.
} // end if.
} // end while.
} // end method.
第一次, MasterList
的第一个元素是“ Name1”,并且列表包含“ 1、2、3”。 下次, MasterList
包含“ Name2”和“ 4、5、6”,但是第一个元素现在包含“ 4、5、6”而不是“ 1、2、3”。 运行一段时间后,“ Name1”,“ Name2”每次都会更新,但是每个元素列表的内容都完全相同,例如,输出应为:
"Name1" -> "1, 2, 3"
"Name2" -> "4, 5, 6"
"Name3" -> "7, 8, 9"
"Name2" -> "4, 5, 6"
"Name3" -> "7, 8, 9"
实际发生的情况:
"Name1" -> "7, 8, 9"
"Name2" -> "7, 8, 9"
"Name3" -> "7, 8, 9"
"Name2" -> "7, 8, 9"
"Name3" -> "7, 8, 9"
试图找出我在这里做错了什么,有什么想法吗? 这是某种参考问题吗?
谢谢! 乔纳森
您一直在重复使用同一列表:
MasterList.Add(new TestClass(Name, Strings)); //<<- Strings is always the same instance
因此,您在列表上所做的任何更改都会传播到所有子类,一个List是一个引用对象,因此当您将其传递给函数时,您不会传递数据结构而是传递对该对象的引用,因此所有这些类指向同一对象。
解决此问题的一种非常简单的方法是替换:
Strings.Clear(); // Clear array.
有:
Strings = new List<string>();
这样,您每次都会将引用传递给新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.