在C#6.0中我可以写:
public int Prop => 777;
Run Code Online (Sandbox Code Playgroud)
但我想使用getter和setter.有办法做下一件事吗?
public int Prop {
get => propVar;
set => propVar = value;
}
Run Code Online (Sandbox Code Playgroud)
Dil*_*ser 89
首先,这不是lambda,尽管语法类似.
它被称为" 表达身体的成员 ".它们与lambdas类似,但仍然根本不同.显然他们无法捕捉像lambdas那样的局部变量.此外,与lambdas不同,它们可以通过他们的名字访问:)如果您尝试将表达式身体属性作为委托传递,您可能会更好地理解这一点.
C#6.0中没有setter的语法,但C#7.0引入了它.
private int _x;
public X
{
get => _x;
set => _x = value;
}
Run Code Online (Sandbox Code Playgroud)
use*_*702 36
C#7为其他成员提供了对二传手的支持:
更多表达身体的成员
表达方法,属性等在C#6.0中是一个很大的打击,但我们不允许它们在各种成员中使用.C#7.0将访问器,构造函数和终结器添加到可以具有表达式主体的事物列表中:
Run Code Online (Sandbox Code Playgroud)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 } }
| 归档时间: |
|
| 查看次数: |
57698 次 |
| 最近记录: |