C# リストの最初の項目を更新するために 3 つのアプローチ (ケース) を試している次のコードがあります (注: Dump() は LINQPad IDE のヘルパー出力メソッドです)。ケース 3 では成功するのに、ケース 2 ではリストの更新が成功しない理由について説明をいただければ幸いです。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;
}