令使用对象初始化语法操作 [英] Order of operations using Object Initializer Syntax

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

问题描述

请问我在其中设置使用对象初始化语法性质完全相同的顺序得到执行?顺序

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

举例来说,如果我这样做:

For instance if I do this:

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

将每个属性得到相同的顺序设置?

will each property get set in the same order?

推荐答案

是的。

道歉越来越中断(我必须做一些实际的工作,每隔一段时间)。该规范没有的明确的说出来,但它使得它pretty的明确IMO第7.6.10.2:

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.

(注意这个词序在这里,而不是设置,我个人认为这是显著,作为一个序列是有序的。)

下面的类重presents点有两个坐标:

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; } }
}

点的实例可以被创建和初始化如下:

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

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

其具有相同的效果

which has the same effect as

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托格森,响应谁基本上说,任何事情,现在可以做到将preserve的顺序。有可能会在未来一段奇特那里的顺序并不preserved在怪异的情况下,你正在做的事情的的比设置属性/场,但是这将取决于这种语言去。

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.

我也将是的非常的警惕的实际写入code取决于这个...

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

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

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