【问题标题】:Error on Constructing Struct in C# [duplicate]在 C# 中构造结构时出错 [重复]
【发布时间】:2014-02-10 10:54:27
【问题描述】:

抱歉标题的笼统,我真的不明白我收到的错误。

所以我关注this tutorial on C#,并且我正在关注“结构和内存管理”部分。

在 5:30 左右,他开始创建一个 Color 结构,所以我跟着一行一行地跟着。一直以来,他的代码都没有显示错误。

我的错误

不过,我的确实如此。其中四个,确切地说:

1) Error 1: Backing field for automatically implemented property 'Color.R' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

错误 2 和 3 与 1 相同,只是将 Color.R 替换为 Color.GColor.B

最后,错误4:

The 'this' object cannot be used before all of its fields are assigned to.

代码

这是我的 Color 结构的代码(同样,我很难注意到我的代码和教程大师的代码之间的任何区别):

public struct Color
{
    public byte R { get; private set; }
    public byte G { get; private set; }
    public byte B { get; private set; }

    public Color(byte red, byte green, byte blue)
    {
        R = red;
        G = green;
        B = blue;
    }

    public static Color Red
    {
        get { return new Color(255, 0, 0); }
    }

    public static Color Green
    {
        get { return new Color(0, 255, 0); }
    }

    public static Color Blue
    {
        get { return new Color(0, 0, 255); }
    }

    public static Color Black
    {
        get { return new Color(0, 0, 0); }
    }

    public static Color White
    {
        get { return new Color(255, 255, 255); }
    }
}

我对 C# 完全陌生,但有一些 PHP 经验,所以我对这里到底发生了什么有点困惑。想法?

【问题讨论】:

    标签: c# struct default-constructor automatic-properties


    【解决方案1】:

    Structs 只能真正使用初始构建的默认构造函数。更改您的构造函数以调用默认值:

    public Color(byte red, byte green, byte blue)
        : this() 
    {
        this.R = red;
        this.G = green;
        this.B = blue;
    }
    

    通过调用this,您正在使用默认构造函数,然后在该特定实例上设置私有值。如果这是 class 而不是 struct 您的代码将毫无问题地运行。

    【讨论】:

    • 太好了,感谢您的帮助。
    猜你喜欢
    • 2021-07-02
    • 2014-12-17
    • 2015-05-30
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多