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.