加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:51:32 所属栏目:百科 来源:网络整理
导读:在C#6.0中使用新的Expression-Bodied Members功能,我们可以采取如下方法: public void Open(){ Console.WriteLine("Opened");} …并将其更改为具有等效功能的简单表达式: public void Open() = Console.WriteLine("Opened"); 但是,对于构造函数,这不是真的
在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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读