编译错误。在struct中使用属性 [英] Compilation error. Using properties with struct

查看:139
本文介绍了编译错误。在struct中使用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释有关struct构造函数的以下错误。如果我将结构更改为
类,错误就会消失。

Please explain the following error on struct constructor. If i change struct to class the erros are gone.

public struct DealImportRequest
{
    public DealRequestBase DealReq { get; set; }
    public int ImportRetryCounter { get; set; }

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




  • 错误CS0188:在将此对象的所有字段都分配给

  • 错误CS0843之前,无法使用此对象返回给呼叫者。考虑从构造函数初始值设定项调用默认的构造函数。

  • 推荐答案

    根据错误消息的建议,您可以通过从构造函数初始化程序调用默认构造函数来解决此问题。

    As the error message recommends, you can resolve this by calling the default constructor from a constructor initializer.

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

    根据语言规范:


    10.7.3自动实现的属性

    当属性为
    时,
    自动实现的属性,该属性
    会自动提供一个隐藏的后备
    字段,并且实现了访问器
    的访问者是从
    读取并写入该后备字段的。 [...]由于
    的后备字段不可访问,因此即使
    包含类型,也只能通过
    属性访问器读取和写入
    。 [...]
    限制还意味着使用
    自动实现属性的结构类型的确定
    赋值只能使用标准
    来实现构造函数的构造函数,因为
    分配给属性本身
    要求结构一定是
    分配。这意味着用户定义的
    构造函数必须调用默认的
    构造函数。

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

    The other (more verbose) alternative, of course, is to manually implement the properties and set the backing fields yourself in the constructor.

    请注意,您拥有的结构是可变的。 不推荐这样做。我建议您将类型设为类(您的编译问题应立即消失)或使类型不可变。假设您提供的代码是 entire 结构,最简单的方法是将设置器设为私有( get; private set; )。当然,您还应确保以后不要再依赖私有访问来修改字段的结构中添加任何变异方法。或者,您可以使用 readonly 后备字段来支持属性,并完全摆脱设置器。

    Do note that the struct you have there is mutable. This is not recommended. I suggest you either make the type a class (your compilation problems should go away immediately) or make the type immutable. The easiest way to accomplish this, assuming the code you have presented is the entire struct, would be to make the setters private (get; private set;). Of course, you should also make sure that you don't add any mutating methods to the struct afterwards that rely on private access to modify the fields. Alternatively, you could back the properties with readonly backing fields and get rid of the setters altogether.

    这篇关于编译错误。在struct中使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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