gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:49:09 25 4
gpt4 key购买 nike

我想获得在自动属性上设置的默认值,以便使用 Fody 进行一些 IL 编织。

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

然而,这假设初始化始终作为构造函数中的第一件事完成。这是一个正确的假设吗?是否有任何边缘情况需要考虑,例如优化?

最佳答案

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

这是关于自动属性初始化器的部分(重点是我的):

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 executedbefore the object is properly initialized. This would mean that there aren’t a whole lot of interestingchoices for what to initialize the auto-properties to. However, primary constructors change that. Autopropertyinitializers 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 areautomatically inserted before the constructor-body.

关于c# - 自动属性初始化 IL 指令顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com