为什么必须在结构上调用:this()以在c#中使用自动属性? [英] Why is it necessary to call :this() on a struct to use automatic properties in c#?

查看:139
本文介绍了为什么必须在结构上调用:this()以在c#中使用自动属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用这样的自动属性在C#中定义结构:

If I define a struct in C# using automatic properties like this:

public struct Address
{
    public Address(string line1, string line2, string city, string state, string zip)
    {
        Line1 = line1;
        Line2 = line2;
        City = city;
        State = state;
        Zip = zip;
    }

    public string Line1 { get; protected set; }
    public string Line2 { get; protected set; }
    public string City { get; protected set; }
    public string State { get; protected set; }
    public string Zip { get; protected set; }
}

当我尝试生成文件时,出现编译错误,提示The 'this' object cannot be used before all of its fields are assigned to.可以通过更改构造函数以对默认构造函数进行链式调用来解决此问题,如下所示:

When I attempt to build the file, I get a compilation error saying The 'this' object cannot be used before all of its fields are assigned to. This can be solved by changing the constructor to make a chained call to the default constructor like this:

public Address(string line1, string line2, string city, string state, string zip): this()
{
    Line1 = line1;
    Line2 = line2;
    City = city;
    State = state;
    Zip = zip;
}

我的问题是,为什么这样做有效?发生了什么?我有一个猜测,我试图通过研究IL来证明这一点,但我只是在开玩笑,如果我认为我可以打破IL.但是我的猜测是,自动属性的工作原理是让编译器在后台为您的属性生成字段.这些字段不能通过代码访问,所有设置和获取都必须通过属性来完成.创建结构时,无法显式定义默认构造函数.因此,在后台,编译器必须生成一个默认的构造函数,该构造函数设置开发人员看不到的字段的值.

My question is, why does this work, and what is happening? I have a guess, and I tried to prove it by looking at IL, but I'm only kidding myself if I think I can break down IL. But my guess is, auto properties work by having the compiler generate fields for your properties behind the scenes. Those fields cannot be accessed through code, all setting and getting must be done through the properties. When creating a struct, a default constructor cannot be explicitly defined. So behind the scenes, the compiler must be generating a default constructor that sets the values of the fields that the developer can't see.

任何人和所有IL向导都欢迎证明或反证我的理论.

Any and all IL wizards are welcome to prove or disprove my theory.

推荐答案

注意:从C#6开始,这不是必需的-但无论如何,您都应该对C#6使用只读的自动实现属性. ..

this()确保就编译器而言,字段已明确分配-将所有字段设置为其默认值.开始访问任何属性之前,必须具有完整的结构.

this() makes sure that the fields are definitely assigned as far as the compiler is concerned - it sets all fields to their default values. You have to have a fully constructed struct before you can start accessing any properties.

这很烦人,但事实就是这样.您确定确实要将此结构作为结构吗?以及为什么在结构(不能从其派生)上使用受保护的setter?

It's annoying, but that's the way it is. Are you sure you really want this to be a struct though? And why use a protected setter on a struct (which can't be derived from)?

这篇关于为什么必须在结构上调用:this()以在c#中使用自动属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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