为什么通用列表索引器显示两种行为

问题描述 投票:1回答:1
static void Main(string[] args)
{
   var vs = new List<Person> { new Person(1) };
   vs[0].IncrementAge();

   Console.WriteLine(vs[0].Age);  // output: 1
}

struct Person
{
   public int Age { get; set; }

   public Person(int age) : this()
   {
      Age = age;
   }

   public int IncrementAge()
   {
      Age++;
      return Age;
   }
}

我理解为什么我们会得到这样的结果。列表索引器返回该元素的副本。没关系。我的问题是,为什么我们在以下代码中没有得到相同的结果?因为我更改了复制元素的值

static void Main(string[] args)
{

   var vs = new List<int> { 1 };
   vs[0] = 2;

   Console.WriteLine(vs[0]);     // output: 2, **why not 1?**
}
c# generics struct indexer
1个回答
0
投票

在此行:

vs[0].IncrementAge();

检索索引0处的值,这将创建struct副本。在副本中,Age递增,副本为然后丢失。它不会保存回列表中。

相反,在这里:

vs[0] = 2;

替换在位置0处的值带有一个新值。这就是为什么更改了[[在列表中。

© www.soinside.com 2019 - 2024. All rights reserved.