ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 自动属性初始化IL指令顺序

2019-05-27 19:58:43  阅读:291  来源: 互联网

标签:c properties cil fody


我想在auto属性上设置默认值,用Fody做一些IL编织.

据我所知,初始化只是一个语法糖,它在构造函数中设置了支持字段.所以我认为使用从最后一个属性的初始化结束到stfld指令的指令创建默认值,该指令设置当前属性的支持字段.

但是,这假设初始化始终是构造函数中的第一件事.这是正确的假设吗?是否有任何边缘情况需要考虑,例如优化?

解决方法:

我找到了这个名为C#中的Upcoming Features的pdf文件,它描述了C#6的新语言功能.

这是关于auto属性初始化器的部分(Emphasis is mine):

The initializer directly initializes the backing field; it doesn’t work through the setter of the autoproperty.

The initializers are executed in order as written, just as – and along with – field initializers.

Just like field initializers, auto-property initializers cannot reference ‘this’ – after all they are executed
before the object is properly initialized.
This would mean that there aren’t a whole lot of interesting
choices for what to initialize the auto-properties to. However, primary constructors change that. Autoproperty
initializers and primary constructors thus enhance each other.

由于字段初始值设定项和自动属性初始值设定项被同等对待,因此C#规范的以下部分也应适用于自动属性初始化.

10.11.3 Constructor execution

Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.

It is useful to think of instance variable initializers and constructor initializers as statements that are
automatically inserted before the constructor-body.

标签:c,properties,cil,fody
来源: https://codeday.me/bug/20190527/1165531.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有