结构初始化和新运算符 [英] Struct initialization and new operator

查看:45
本文介绍了结构初始化和新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有两个类似的结构,每个结构都包含一个整数,但是后者实现了get/set访问器.

I have two similar structs in C#, each one holds an integer, but the latter has get/set accessors implemented.

为什么在分配 a 字段之前,必须使用 new 运算符初始化 Y 结构?当我使用 new 初始化 y 时,它仍然是一种值类型吗?

Why do I have to initialize the Y struct with new operator prior to assigning the a field? Is y still a value type when I init it with new?

public struct X
{
    public int a;
}

public struct Y
{
    public int a { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        X x;
        x.a = 1;

        Y y;
        y.a = 2; // << compile error "unused local variable" here

        Y y2 = new Y();
        y2.a = 3;
    }
}

推荐答案

一个有效而另一个无效的原因是,您不能在未初始化的对象上调用方法.属性设置器也是方法.

The reason one is valid while the other is not is that you cannot call methods on uninitialised objects. Property setters are methods too.

public struct X
{
    public int a;
    public void setA(int value)
    { this.a = value; }
}

public struct Y
{
    public int a { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        X x;
        x.setA(1); // A: error
        x.a = 2; // B: okay

        Y y;
        y.a = 3; // C: equivalent to A
    }
}

不允许的原因是属性设置器可以观察到对象的未初始化状态.调用者不知道属性设置器是仅设置一个字段,还是设置更多.

The reason that is not allowed is that the property setter could observe the uninitialised state of the object. The caller does not know whether the property setter merely sets a field, or does more than that.

这篇关于结构初始化和新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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