Lambda for getter和setter of property

在C#6.0中我可以写:

public int Prop => 777; 

但我想使用getter和setter。 有办法做下一件事吗?

 public int Prop { get => propVar; set => propVar = value; } 

首先,这不是lambda,尽管语法类似。

它被称为“ 表达身体的成员 ”。 它们与lambdas类似,但仍然根本不同。 显然他们无法捕捉像lambdas这样的局部变量。 此外,与lambdas不同,它们可以通过他们的名字访问:)如果您尝试将表达式身体属性作为委托传递,您可能会更好地理解这一点。

C#6.0中没有setter的语法,但C#7.0引入了它 。

 private int _x; public X { get => _x; set => _x = value; } 

C#7为其他成员提供了对二传手的支持:

更多表达身体的成员

表达方法,属性等在C#6.0中是一个很大的打击,但我们不允许在各种成员中使用它们。 C#7.0将访问器,构造函数和终结器添加到可以具有表达式主体的事物列表中:

 class Person { private static ConcurrentDictionary names = new ConcurrentDictionary(); private int id = GetId(); public Person(string name) => names.TryAdd(id, name); // constructors ~Person() => names.TryRemove(id, out _); // finalizers public string Name { get => names[id]; // getters set => names[id] = value; // setters } } 

没有这样的语法,但旧的语法非常相似:

  private int propVar; public int Prop { get { return propVar; } set { propVar = value; } } 

要么

 public int Prop { get; set; }