我有以下代码,我正在尝试 3 种方法(案例)来更新 C# 列表中的第一项(注意:Dump() 是 LINQPad IDE 中的辅助输出方法)。我希望能解释一下为什么案例 2 没有成功更新列表,而案例 3 却成功了。first 和 list[0] 都是对列表中第一项的引用,并且在分配直接引用时应该表现相同。显然不是...
void Main()
{
Person first = null;
List<Person> list = CreateList(out first);
//Case 1
//This updates the list
first.fname = "Third";
list.Dump(); //outputs third, second
//Case 2
//This does not update the list
list = CreateList(out first);
first= new Person() { fname="Third"};
list.Dump(); //outputs first, second
//Case 3
//This updates the list
list = CreateList(out first);
list[0] = new Person() { fname="Third"};
list.Dump(); //outputs third, second
}
List<Person> CreateList(out Person first)
{
var list = new List<Person>
{
new Person() { fname="First", lname = ""},
new Person() { fname="Second", lname = ""}
};
first = list.Find( x => x.fname == "First");
return list;
}
// Define other methods and classes here
class Person
{
public string fname;
public string lname;
}