【问题标题】:Parameterless constructor on struct not supported in C# 6 [duplicate]C# 6 不支持结构上的无参数构造函数 [重复]
【发布时间】:2017-03-19 15:34:53
【问题描述】:

我有一个带有无参数构造函数的结构:

struct Coordinate
{
    public Coordinate() : this(4, 5, 6)
    {

    }
    public Coordinate(float x, float y, float z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public float X { get; private set; }
    public float Y { get; private set; }
    public float Z { get; private set; }
}

我将项目属性中的语言属性设置为 C#,但仍然出现编译错误。

Error CS0568 Structs cannot contain explicit parameterless constructors

【问题讨论】:

  • 它已被讨论为潜在的 C# 6.0 功能,但没有成功。
  • 您有问题吗?
  • @IvanStoev 我读过,但也在 [MSDN([msdn.microsoft.com/en-gb/magazine/dn879355.aspx).好的,那就清楚了。听起来确实令人困惑。
  • @JLRishe 我做到了,这就是我收到错误的原因。不过,伊万已经把它清理干净了。
  • @Phylyp 感谢您的链接,我想我们可以简单地关闭这个骗局。

标签: c# struct constructor c#-6.0


【解决方案1】:

遗憾的是,C# 不允许定义无参数构造函数。 一种解决方法是将默认值定义为属性。

public static Coordinate defaultValue { get { return new Coordinate (7, 6, 3); } }

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2013-12-24
    • 2016-09-19
    相关资源
    最近更新 更多