2015-06-26 65 views
22

我的理解是现在允许使用结构体中的无参数构造函数。C#结构中的无参数构造函数6

但下面给我一个编译错误,在2015年VS社区

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) { } 
} 

错误:“的Structs不能包含明确的参数构造函数”

任何人都知道为什么吗?

+0

此链接似乎表明它应该在VS 2015中用C#6工作:http://www.c-sharpcorner.com/UploadFile/0e8478/parameterless-constructors-in-structs/不知道为什么它不起作用为你。 –

+0

这是另一篇文章,有一些注意事项:http://www.volatileread.com/Wiki/Index?id=1091但没有解释你的特定问题。您是否检查过以确保您的项目针对的是项目设置中的.NET 6.0框架? –

回答

38

该功能出现在C#6.0的旧版预览中,这就是为什么一些文章谈论它。但是它被删除了,所以在VS 2015 RC发行的版本中不存在。

具体而言,更改已在pull request #1106中恢复,有关issue #1029中基本原理的更多信息。引用弗拉基米尔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.

[…]

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.

+0

有趣的是:虽然该功能已从C#中删除,但它保存在[tag:vb.net]中,可以在那里使用。 OP的代码示例转换为VB(所有构造函数都有名称'New')。 – miroxlav

+0

@miroxlav [我不认为这是真的。](http://stackoverflow.com/q/32179495/41071) – svick

+1

哦,我明白了,虽然没有明确说明,但这个问答只讨论*非静态*。静态无参数'struct'构造函数在C#和VB中都可以工作。 (经测试。) – miroxlav

0

我不知道为什么,但是,这是允许的:

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

这是否解决问题了吗?

+6

你定义的构造函数不会被调用,如果你不使用任何参数,请参见[这里](https://stackoverflow.com/questions/27145633/unintuitive-behaviour-with-struct-initialization-and-default-arguments ?LQ = 1) – gartenriese