自动属性和结构不混合? [英] Automatic Properties and Structures Don't Mix?

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

问题描述

在回答这篇博文时,我在一些小结构上胡思乱想,意外地发现了以下内容:

Kicking around some small structures while answering this post, I came across the following unexpectedly:

以下结构,使用 int 字段是完全合法的:

The following structure, using an int field is perfectly legal:

struct MyStruct
{ 
    public MyStruct ( int size ) 
    { 
        this.Size = size; // <-- Legal assignment.
    } 

    public int Size; 
}

但是,使用自动属性无法编译以下结构:

However, the following structure, using an automatic property does not compile:

struct MyStruct
{ 
    public MyStruct ( int size ) 
    { 
        this.Size = size; // <-- Compile-Time Error!
    } 

    public int Size{get; set;}
}

返回的错误是在分配所有字段之前不能使用‘this’对象".我知道这是结构的标准过程:必须从结构的构造函数内直接分配任何属性的支持字段(而不是通过属性的 set 访问器).

The error returned is "The 'this' object cannot be used before all of its fields are assigned to". I know that this is standard procedure for a struct: the backing field for any property must be assigned directly (and not via the property's set accessor) from within the struct's constructor.

解决方案是使用显式支持字段:

A solution is to use an explicit backing field:

struct MyStruct
{ 
    public MyStruct(int size)
    {
        _size = size;
    }

    private int _size;

    public int Size
    {
        get { return _size; }
        set { _size = value; }
    }
}

(注意 VB.NET 不会有这个问题,因为在 VB.NET 中所有字段在第一次创建时都会自动初始化为 0/null/false.)

(Note that VB.NET would not have this issue, because in VB.NET all fields are automatically initialized to 0/null/false when first created.)

在 C# 中使用带有结构的自动属性时,这似乎是一个不幸的限制.从概念上思考,我想知道这是否不是一个合理的地方,允许在结构的构造函数中调用属性集访问器的异常,至少对于自动属性?

This would seem to be an unfortunate limitation when using automatic properties with structs in C#. Thinking conceptually, I was wondering if this wouldn't be a reasonable place for there to be an exception that allows the property set accessor to be called within a struct's constructor, at least for an automatic property?

这是一个小问题,几乎是边缘情况,但我想知道其他人对此有何看法...

This is a minor issue, almost an edge-case, but I was wondering what others thought about this...

推荐答案

从 C# 6 开始:这不再是问题

From C# 6 onward: this is no longer a problem

Becore C# 6,您需要调用默认构造函数才能使其工作:

Becore C# 6, you need to call the default constructor for this to work:

public MyStruct(int size) : this()
{
    Size = size;
}

这里一个更大的问题是你有一个可变结构.这绝不是个好主意.我会做到的:

A bigger problem here is that you have a mutable struct. This is never a good idea. I would make it:

public int Size { get; private set; }

技术上不是一成不变的,但足够接近了.

Not technically immutable, but close enough.

使用最新版本的 C#,您可以改进这一点:

With recent versions of C#, you can improve on this:

public int Size { get; }

现在可以在构造函数中赋值.

This can now only be assigned in the constructor.

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

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