如何在 C# 中初始化结构 [英] How to initialize a struct in C#

查看:66
本文介绍了如何在 C# 中初始化结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以在 C# 中初始化一个结构:

I have some code to initialize a struct in C#:

namespace Practice
{
    public struct Point
    {
        public int _x;
        public int _y;

        public int X
        {
            get { return _x; }
            set { _x = value; }
        }

        public int Y
        {
            get { return _y; }
            set { _y = value; }
        }

        public Point(int x, int y)
        {
            _x = x;
            _y = y;
        }    
    }    

    class Practice
    {
        public static void Main()
        {
            Point p1;
            p1.X = 1;
            p1.Y = 2;
        }
    }
}

上面的代码给出了编译错误:

The above code gives a compiler error:

错误 CS0165:使用未分配的本地变量'p1'

error CS0165: Use of unassigned local variable 'p1'

为什么会抛出这个错误?

Why is this error being thrown?

推荐答案

你不能在结构中使用 property,直到它知道所有 fields 都已被填充在.

You can't use a property in a struct until it knows all the fields have been filled in.

例如,在您的情况下,这应该编译:

For example, in your case this should compile:

Point p1;
p1._x = 1;
p1._y = 2;
int x = p1.X; // This is okay, now the fields have been assigned

请注意您如何不必在此处显式调用构造函数...尽管在封装良好的结构中您几乎总是必须这样做.您可以摆脱这种情况的唯一原因是因为您的字段是公开的.艾克.

Note how you don't have to explicitly call a constructor here... although in well-encapsulated structs you almost always would have to. The only reason you can get away with this is because your fields are public. Ick.

但是,我强烈建议您不要无论如何都使用可变结构.如果你真的想要一个结构,让它不可变并将值传递给构造函数:

However, I would strongly advise you not to use a mutable struct anyway. If you really want a struct, make it immutable and pass the values into the constructor:

public struct Point
{
    private readonly int x;
    public int X { get { return x; } }

    private readonly int y;
    public int Y { get { return y; } }

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

...

Point p1 = new Point(1, 2);

这篇关于如何在 C# 中初始化结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆