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

查看:150
本文介绍了如何在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'

为什么会引发此错误?

推荐答案

在知道所有字段已被填充之前,您不能在结构中使用属性内.

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天全站免登陆