简体   繁体   English

C#6结构中的无参数构造函数

[英]Parameterless constructors in structs for C# 6

My understanding is that Parameterless constructors in structs are now allowed. 我的理解是现在允许结构中的无参数构造函数。

But the following gives me a compile error in VS 2015 Community 但是下面的代码在VS 2015社区中给出了编译错误

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name, int age) { Name = name; Age = age; } 
    public Person() : this("Jane Doe", 37) { } 
}

Error: "Structs cannot contain explicit parameterless constructors" 错误:“结构不能包含显式无参数构造函数”

Anyone know why? 谁知道为什么?

The feature was present in older previews of C# 6.0, which is why some articles talk about it. 该功能出现在较早的C#6.0预览中,这就是为什么有些文章谈论它。 But it was then removed and so it's not present in the version distributed with VS 2015 RC. 但它随后被移除,因此在VS 2015 RC分发的版本中不存在。

Specifically, the change was reverted in pull request #1106 , with more information about the rationale in issue #1029 . 具体而言,在拉取请求#1106中还原了更改,其中包含有关问题#1029的基本原理的更多信息。 Quoting Vladimir Sadov: 引用弗拉基米尔萨多夫:

As we performed more and more testing, we kept discovering cases where parameterless struct constructors caused inconsistent behavior in libraries or even in some versions of CLR. 随着我们执行越来越多的测试,我们不断发现无参数构造函数在库中甚至在某些版本的CLR中导致不一致行为的情况。

[…] [...]

After reconsidering the potential issues arising from breaking long standing assumptions, we decided it was best for our users to restore the requirement on struct constructors to always have formal parameters. 在重新考虑破坏长期假设所引起的潜在问题之后,我们认为最好让我们的用户恢复结构构造函数的要求,使其始终具有形式参数。

I'm not sure why, however, this is allowed: 我不确定为什么这是允许的:

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name = null, int age = 0) { Name = name; Age = age; } 
}

Does that solve your problem? 这会解决你的问题吗?

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

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