getter 的 Lambda 和 属性 的 setter
Lambda for getter and setter of property
在 C# 6.0 中我可以写:
public int Prop => 777;
但我想使用 getter 和 setter。
有什么办法可以做下一步吗?
public int Prop {
get => propVar;
set => propVar = value;
}
首先,这不是 lambda,尽管语法相似。
它被称为“expression-bodied members”。它们类似于 lambda,但仍存在根本区别。显然它们不能像 lambda 那样捕获局部变量。此外,与 lambda 不同的是,它们可以通过名称访问:) 如果您尝试将表达式主体 属性 作为委托传递,您可能会更好地理解这一点。
C# 6.0 中没有这样的 setter 语法,但是 C# 7.0 introduces it。
private int _x;
public int X
{
get => _x;
set => _x = value;
}
没有这样的语法,但旧语法非常相似:
private int propVar;
public int Prop
{
get { return propVar; }
set { propVar = value; }
}
或者
public int Prop { get; set; }
C# 7 带来了对 setter 的支持,以及其他成员:
More expression bodied members
Expression bodied methods, properties etc. are a big hit in C# 6.0,
but we didn’t allow them in all kinds of members. C# 7.0 adds
accessors, constructors and finalizers to the list of things that can
have expression bodies:
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
}
}
在 C# 6.0 中我可以写:
public int Prop => 777;
但我想使用 getter 和 setter。 有什么办法可以做下一步吗?
public int Prop {
get => propVar;
set => propVar = value;
}
首先,这不是 lambda,尽管语法相似。
它被称为“expression-bodied members”。它们类似于 lambda,但仍存在根本区别。显然它们不能像 lambda 那样捕获局部变量。此外,与 lambda 不同的是,它们可以通过名称访问:) 如果您尝试将表达式主体 属性 作为委托传递,您可能会更好地理解这一点。
C# 6.0 中没有这样的 setter 语法,但是 C# 7.0 introduces it。
private int _x;
public int X
{
get => _x;
set => _x = value;
}
没有这样的语法,但旧语法非常相似:
private int propVar;
public int Prop
{
get { return propVar; }
set { propVar = value; }
}
或者
public int Prop { get; set; }
C# 7 带来了对 setter 的支持,以及其他成员:
More expression bodied members
Expression bodied methods, properties etc. are a big hit in C# 6.0, but we didn’t allow them in all kinds of members. C# 7.0 adds accessors, constructors and finalizers to the list of things that can have expression bodies:
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 } }