加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 编译错误.使用结构体的属性

发布时间:2020-12-15 06:43:44 所属栏目:百科 来源:网络整理
导读:请解释struct构造函数上的以下错误.如果我将结构体更改为类 错误消失了. public struct DealImportRequest{ public DealRequestBase DealReq { get; set; } public int ImportRetryCounter { get; set; } public DealImportRequest(DealRequestBase drb) { D
请解释struct构造函数上的以下错误.如果我将结构体更改为类
错误消失了.
public struct DealImportRequest
{
    public DealRequestBase DealReq { get; set; }
    public int ImportRetryCounter { get; set; }

    public DealImportRequest(DealRequestBase drb)
    {
        DealReq = drb;
        ImportRetryCounter = 0;
    }
}

>错误CS0188:在这个对象的所有字段都被赋值之前,不能使用’this’对象
>错误CS0843:自动实现属性的备份字段
在将控制权返回给调用者之前,必须完全指定“DealImportRequest.DealReq”.考虑从构造函数初始化器调用默认构造函数.

解决方法

正如错误消息推荐的那样,您可以通过从构造函数初始化程序调用默认构造函数来解决此问题.
public DealImportRequest(DealRequestBase drb) : this()
{
   DealReq = drb;
   ImportRetryCounter = 0;
}

从语言规范:

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.

另一个(更冗长)的替代方法当然是手动实现属性并在构造函数中自行设置后备字段.

请注意你拥有的结构是可变的. This is not recommended.我建议你把类型做成一个类(你的编译问题应该马上消失),或使类型不可变.实现这一点的最简单的方法是假设你所呈现的代码是整个结构体,将使setter为private(get; private set;).当然,您还应该确保不要在结构之后添加任何依赖于私有访问来修改字段的突变方法.或者,您可以使用只读备份字段来返回属性,并完全删除setter.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读