C# 使用lambda表达式时,列表中的属性已更改
当我使用lambda表达式时,我不知道为什么列表中的项发生了更改。 这是我的密码C# 使用lambda表达式时,列表中的属性已更改,c#,lambda,C#,Lambda,当我使用lambda表达式时,我不知道为什么列表中的项发生了更改。 这是我的密码 using System; using System.Collections.Generic; using System.Linq; public class test { public string id { get; set; } public string name { get; set; } public string no { get; set; } } public clas
using System;
using System.Collections.Generic;
using System.Linq;
public class test
{
public string id { get; set; }
public string name { get; set; }
public string no { get; set; }
}
public class Program
{
public static List<test> a;
public static List<test> b = new List<test>();
public static List<test> a_list()
{
List<test> c = new List<test>();
c.Add(new test() { id = "_01", name=null, no="1"});
c.Add(new test() { id = "_02", name=null, no="2"});
return c;
}
public static void Main()
{
a = a_list();
string key = "_01";
//
test i = new test();
i = a.First(x => x.id.Equals(key));
i.name = "xxxxxxx";
b.Add(i);
//
Console.WriteLine("id:"+a[0].id+"\nName:"+a[0].name+"\nno:"+a[0].no);
Console.WriteLine("id:"+b[0].id+"\nName:"+b[0].name+"\nno:"+b[0].no);
Console.ReadLine();
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
公开课考试
{
公共字符串id{get;set;}
公共字符串名称{get;set;}
公共字符串no{get;set;}
}
公共课程
{
公共静态列表a;
公共静态列表b=新列表();
公共静态列表a_List()
{
列表c=新列表();
c、 添加(newtest(){id=“\u 01”,name=null,no=“1”});
c、 添加(newtest(){id=“\u 02”,name=null,no=“2”});
返回c;
}
公共静态void Main()
{
a=a_list();
字符串键=“_01”;
//
测试i=新测试();
i=a.First(x=>x.id.Equals(key));
i、 name=“xxxxxxx”;
b、 加(i);
//
Console.WriteLine(“id:+a[0]。id+”\n名称:+a[0]。名称+”\n否:+a[0]。否);
Console.WriteLine(“id:+b[0]。id+”\n名称:+b[0]。名称+”\n否:+b[0]。否);
Console.ReadLine();
}
}
这就是结果
id:_01
姓名:xxxxxxx
否:1
id:_01
姓名:xxxxxxx
否:1
为什么[0]等于“xxxxxxx”?(对不起,我的英语不好)这里:
i = a.First(x => x.id.Equals(key));
i.name = "xxxxxxx";
i
和a.First()
现在是对同一对象的引用。修改该对象上的属性将影响这两个对象,因为它们是指向同一对象的指针。基本上,代码所做的是:
- 它创建了一个包含两个元素的列表(
)a
- 它获取其第一个元素并修改该元素的值
- 它获取该元素并将其添加到第二个列表(
)b
因此,结果是您有两个列表-一个(
a
)包含两个元素,另一个(b
)只有一个,但是(这里是重要的一点)-它与a
中的第一个元素完全相同。因此,当您编写两个列表的第一个元素时,结果是相等的。想象您有一个摄像头指向一辆汽车。当车门打开时,您可以通过摄像头看到车门,但摄像头不是汽车
现在你的朋友在远处也把他的相机对准了汽车。你们都可以看到门的打开和关闭,以及灯光等等
变量就像照相机,汽车就是它指向的对象。
如果你关掉或摧毁其中一个摄像头,那辆车仍然在那里。事实上,如果你摧毁了两个摄像头,汽车仍然在那里(直到垃圾收集)
请参阅这篇优秀的文章:没有真正理解您在这里提出的问题-
(…
返回对测试对象的引用,然后对其进行更改。您希望发生什么?您希望发生什么?因为这是您设置的。您希望该赋值不起作用吗?您只需要使用first
请求第一个,谢谢您的回答,但我刚刚添加了变量“i”添加到列表“b”中,那么为什么列表“a”中的元素也会更改?感谢您的回复,但我刚刚将变量“i”添加到列表“b”中,那么为什么列表“a”中的元素会更改“还有变化吗?因为a
中的第一个元素是i
,它是这两个元素的第一个元素。你不能用物理框的形式来考虑列表,而应该考虑一个我可以找到实际对象的位置列表。你的两个列表(至少在第一个元素上)都指向同一个对象——你刚刚修改过的对象。