使用对象初始值设定项语法的操作顺序 [英] Order of operations using Object Initializer Syntax

查看:25
本文介绍了使用对象初始值设定项语法的操作顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用对象初始值设定项语法设置属性的顺序是否以完全相同的顺序执行?

Does the order in which I set properties using the object initializer syntax get executed in the exact same order?

例如,如果我这样做:

var s = new Person { FirstName = "Micah",
                     LastName = "Martin",
                     IsLoaded = true
                   }

每个属性的设置顺序是否相同?

will each property get set in the same order?

推荐答案

是.

很抱歉被打扰(实际上我必须经常做一些工作).规范没有明确说出来,但它在第 7.6.10.2 节中让 IMO 非常清楚:

Apologies for getting interrupted (I have to actually do some work every so often). The spec doesn't explicitly say it, but it makes it pretty clear IMO in section 7.6.10.2:

对象初始值设定项由一系列成员初始值设定项组成,用 { 和 } 标记括起来并用逗号分隔.

An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas.

(注意这里的序列"一词,而不是设置".我个人认为这很重要,因为序列是有序的.)

以下类表示具有两个坐标的点:

The following class represents a point with two coordinates:

public class Point
{
    int x, y;
    public int X { get { return x; } set { x = value; } }
    public int Y { get { return y; } set { y = value; } }
}

Point 的实例可以按如下方式创建和初始化:

An instance of Point can be created and initialized as follows:

Point a = new Point { X = 0, Y = 1 };

效果与

Point __a = new Point();
__a.X = 0;
__a.Y = 1; 
Point a = __a;

其中 __a 是一个不可见且无法访问的临时变量.

where __a is an otherwise invisible and inaccessible temporary variable.

我收到了 Mads Torgersen 的回复,他基本上说现在可以做的任何事情都会保留订单.将来可能会出现一些奇怪的情况,在奇怪的情况下,您正在做一些其他而不是设置属性/字段的事情,但那将取决于语言的发展方向.

I've had a response from Mads Torgersen, who has basically said that anything which can be done now will preserve the order. There may be some oddities in future where the order is not preserved in weird cases where you're doing something other than setting a property/field, but that will depend on where the language goes.

值得指出的是,这里实际上有很多步骤 - 参数评估的执行顺序(即 RHS 位)和赋值的执行顺序.例如,如果您有:

It's worth pointing out that there are actually lots of steps going on here - there's the order of execution of the evaluation of the arguments (i.e. the RHS bits) and the order of execution of the assignments. For example, if you have:

new Foo
{
    A = X,
    B = Y
}

以下所有订单都是可能的,同时仍然保持实际财产执行的顺序(A 和 B):

all the following orders are possible while still maintaining the order of the actual property execution (A and B):

  • 计算X,分配给A,计算Y,分配给B
  • 计算X,计算Y,赋值给A,赋值给B
  • 评估Y,评估X,分配给A,分配给B

我相信第一个选项是实际采用的选项,但这只是为了证明它比表面上看起来更重要.

I believe the first option is the one actually taken, but this was just to demonstrate that there's more to it than meets the eye.

我也会非常警惕实际编写依赖于此的代码......

I would also be very wary of actually writing code which depends on this...

这篇关于使用对象初始值设定项语法的操作顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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