简体   繁体   English

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

[英]Why can't we use expression-bodied constructors?

Using the new Expression-Bodied Members feature in C# 6.0, we can take a method like this: 使用C#6.0中新的Expression-Bodied Members功能,我们可以采用如下方法:

public void Open()
{
    Console.WriteLine("Opened");
}

...and change it to a simple expression with equivalent functionality: ...并将其更改为具有同等功能的简单表达式:

public void Open() => Console.WriteLine("Opened");

This is not true for constructors, however. 然而,对于构造函数而言,情况并非如此。 Code such as this doesn't compile: 像这样的代码不能编译:

private DbManager() => Console.WriteLine("ctor");

Nor does this: 这也不是:

private DbManager() => {}

Is there any reason why constructors cannot benefit from the expression-bodied members feature, and must be declared the traditional way? 是否有任何理由为什么构造函数不能从表达体成员特征中受益,并且必须以传统方式声明?

It would be more confusing than useful. 它会比实用更令人困惑。 Especially when you add a call to another constructor. 特别是当您向另一个构造函数添加调用时。

Here's the direct quote from the design notes: 这是设计说明的直接引用:

Constructors have syntactic elements in the header in the form of this(…) or base(…) initializers which would look strange just before a fat arrow. 构造函数在头部中以这个(...)或base(...)初始化器的形式具有语法元素,这些元素在胖箭头之前看起来很奇怪。 More importantly, constructors are almost always side-effecting statements, and don't return a value. 更重要的是,构造函数几乎总是副作用语句,并且不返回值。

From C# Design Notes for Nov 4, 2013 来自2013年11月4日的C#设计说明

In a more general way: 以更一般的方式:

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. 总而言之,表达式主体允许在方法和用户定义的运算符(包括转换)上,它们表示从函数返回的值,以及表示从getter返回的值的属性和索引器,并暗示没有setter 。

Now that the c# 7.0 has been released it is possible to use expression-bodied constructors. 现在已经发布了c#7.0,可以使用表达式构造函数。

private DbManager() => Console.WriteLine("ctor");

works fine in c# 7.0 在c#7.0中工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM