gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:16:31 25 4
gpt4 key购买 nike

我的理解是现在允许结构中的无参数构造函数。

但是以下在 VS 2015 Community 中给我一个编译错误

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

错误:“结构不能包含显式无参数构造函数”

有人知道为什么吗?

最佳答案

此功能在 C# 6.0 的较旧预览版中存在,这就是为什么有些文章会谈论它的原因。但它随后被删除,因此它不存在于随 VS 2015 RC 分发的版本中。

具体来说,更改已在 pull request #1106 中恢复, 更多关于 issue #1029 中的基本原理的信息.引用弗拉基米尔·萨多夫 (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.

[…]

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.

The feature was then added back in C# 10.0.

关于c# - C# 6 结构中的无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com