首页 > 解决方案 > 引用其他类元素的列表

问题描述

class LINE
{
    public List<string> data = new List<string>();
}

class A
{
    public string num { get; set; }
    public string name { get; set; }
}

我有 2 个类,我想做的是,当更改listA的值时,它也会在LINES列表上更改。

List<A> listA = new List<A>();
List<LINE> LINES = new List<LINE>();

A temp = new A();
temp.name = "test";
temp.num = "10";
listA.Add(temp);

LINE l = new LINE();
l.data.Add(temp.num);
l.data.Add(temp.name);
LINES.Add(l);

listA.Last().num = "30"; // it changes LINES value as well

标签: c#

解决方案


您的示例将在 C++ 中工作,但 C# 不是 C++。

C# 中的每个字符串都是 uniq 对象。List,存储对字符串的引用。在你的情况下

temp.num = "10"; //field num has referenced to string "10"
l.data[0];// Referenced to string "10" too

所以,当你打电话

listA.Last().num = "30"; //now temp.num has referenced to string "30"
l.data[0];// But this still referenced to string "10" too

在 C++ 中,您使用 std::string 作为 char*,但在 C#(以及 Java)中,您使用引用。因此,当您编写 listA.Last().num = "30" 时,您会创建新的 char* 并指向它。(没变)


推荐阅读