c# - 引用其他类元素的列表
问题描述
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# 中的每个字符串都是 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* 并指向它。(没变)
推荐阅读
- sockets - 在 Haskell 中启动 TCP 服务器
- mysql - 如何在 SQL 查询中过滤 IP 地址范围?
- java - 使用“对象”代替特定类型有什么问题?
- java - Spring Security 访问被拒绝产生 HTTP 405
- c# - 是否可以在 C# 中编写代码以在我打开 Word 文档时创建表格?
- java - 支持 Java 的 VS Code 中的调试控制台错误地将输出中的行拆分为 sysout.printf/format
- php - 删除帖子时如何删除laravel中的所有相关评论,喜欢和通知
- php - GuzzleHttp 访问令牌为空
- python - 如果控制台窗口对于文本来说太小,则回车在 linux 上不起作用
- flutter - 如何在一行中添加相同的矩形 10 次