为什么我们不能使用 expression-bodied 构造函数?
Why can't we use expression-bodied constructors?
使用 C# 6.0 中新的 Expression-Bodied Members 功能,我们可以采用如下方法:
public void Open()
{
Console.WriteLine("Opened");
}
...并将其更改为具有等效功能的简单表达式:
public void Open() => Console.WriteLine("Opened");
然而,对于构造函数而言,情况并非如此。这样的代码无法编译:
private DbManager() => Console.WriteLine("ctor");
这也不行:
private DbManager() => {}
为什么构造函数不能从表达式体成员功能中受益,而必须以传统方式声明,有什么原因吗?
它会更混乱而不是有用。特别是当您添加对另一个构造函数的调用时。
这里直接引用设计说明:
Constructors have syntactic elements in the header in the form of this(…) or base(…) initializers which would look strange just before a fat arrow. More importantly, constructors are almost always side-effecting statements, and don’t return a value.
来自C# Design Notes for Nov 4, 2013
更一般的方式:
To summarize, expression bodies are allowed on methods and user defined operators (including conversions), where they express the value returned from the function, and on properties and indexers where they express the value returned from the getter, and imply the absence of a setter.
现在 c# 7.0 已经发布,可以使用表达式主体构造函数。
private DbManager() => Console.WriteLine("ctor");
在 c# 7.0 中工作正常
使用 C# 6.0 中新的 Expression-Bodied Members 功能,我们可以采用如下方法:
public void Open()
{
Console.WriteLine("Opened");
}
...并将其更改为具有等效功能的简单表达式:
public void Open() => Console.WriteLine("Opened");
然而,对于构造函数而言,情况并非如此。这样的代码无法编译:
private DbManager() => Console.WriteLine("ctor");
这也不行:
private DbManager() => {}
为什么构造函数不能从表达式体成员功能中受益,而必须以传统方式声明,有什么原因吗?
它会更混乱而不是有用。特别是当您添加对另一个构造函数的调用时。
这里直接引用设计说明:
Constructors have syntactic elements in the header in the form of this(…) or base(…) initializers which would look strange just before a fat arrow. More importantly, constructors are almost always side-effecting statements, and don’t return a value.
来自C# Design Notes for Nov 4, 2013
更一般的方式:
To summarize, expression bodies are allowed on methods and user defined operators (including conversions), where they express the value returned from the function, and on properties and indexers where they express the value returned from the getter, and imply the absence of a setter.
现在 c# 7.0 已经发布,可以使用表达式主体构造函数。
private DbManager() => Console.WriteLine("ctor");
在 c# 7.0 中工作正常