C# · 12月 27, 2021

c# – 为什么我们不能使用表达式构造函数?

在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.