在结构自动实现的属性不能分配 [英] Automatically implemented property in struct can not be assigned

查看:266
本文介绍了在结构自动实现的属性不能分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的下一个code:

struct T 
{
    public T(int u) 
    { 
     this.U = 10; //Errors are here
     }

    public int U { get; private set;  }
}

C#编译器给我一对在规定路线的错误: 1)自动实现的属性TestConsoleApp.Program.TU支持字段必须全部分配之前控制返回给调用者。考虑从调用构造函数初始化的默认构造函数。 2)这对象不能被使用之前所有字段被分配给

C# compiler give me a pair of errors in stated line: 1) Backing field for automatically implemented property 'TestConsoleApp.Program.T.U' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. 2) The 'this' object cannot be used before all of its fields are assigned to

我做错了什么?帮我明白了。

What I do wrong? Help me understand.

推荐答案

从C#规格:

10.7.3自动实现的属性。

10.7.3 Automatically implemented properties

当一个属性被指定为一个自动实现的属性,   一个隐藏的后备字段将自动变为可用的属性,   和访问实现读取和写入该   支持字段。

When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backing field.

[删除]

由于支持字段不可访问,就可以读出和写入   只有通过属性访问器,即使在包含类型。

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

[删除]

此限制也意味着一定的结构类型分配   与自动实现属性只能通过实现   该结构的标准构造,因为分配给该属性   本身就需要被明确赋值的结构。这意味着   用户定义的构造函数必须调用默认的构造函数。

This restriction also means that definite assignment of struct types with auto-implemented properties can only be achieved using the standard constructor of the struct, since assigning to the property itself requires the struct to be definitely assigned. This means that user-defined constructors must call the default constructor.

所以,你需要这样的:

struct T 
{
    public T(int u)
        : this()
    { 
        this.U = u;
    }

    public int U { get; private set; }
}

这篇关于在结构自动实现的属性不能分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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