在C#6.0中,我可以编写:
public int Prop => 777;
但是我想使用getter和setter。有什么办法可以做下一个?
public int Prop {
get => propVar;
set => propVar = value;
}
在C#6.0中,我可以编写:
public int Prop => 777;
但是我想使用getter和setter。有什么办法可以做下一个?
public int Prop {
get => propVar;
set => propVar = value;
}
Answers:
C#7带来了对setter的支持,以及其他成员:
更多表情浓郁的成员
表达式合并的方法,属性等在C#6.0中很受欢迎,但是我们不允许所有类型的成员使用它们。C#7.0将访问器,构造函数和终结器添加到可以具有表达式主体的事物列表中:
class Person { private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>(); 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; }
=>值得使用语法,但是对于自动实现的属性却太复杂了?