c#中的不可变结构

Immutable structure in c#

我的代码如下:

struct Name
{

private int age;

public int Age
{
  get
  {
    return age;
  }
  set
  {
    age = Age;
  }
}
public Name(int a)
{
  age = a;
}

};

  class Program
  {
    static void Main(string[] args)
    {
      Name myName = new Name(27);
      Console.WriteLine(myName.Age);
      myName.Age = 30;
      Console.WriteLine(myName.Age);
    }
  }

如您所见,我正在尝试使用 属性 更改年龄值。但是我得到的值仍然与创建结构名称对象时传递的值相同。我知道 struct 在 C# 中是不可变的,但我想我能够改变它们中的字段。我很迷茫。谁能给我解释一下这是怎么回事?

默认情况下,C# 中的结构不是不可变的。要将结构标记为不可变,您应该使用 readonly modifier on the struct. The reason your properties aren't updating is that your syntax is wrong. You should use the value 关键字取消引用提供给 setter.

value
public int Age
{
  get
  {
    return age;
  }
  set
  {
    age = value;          // <-- here
  }
}