简体   繁体   English

新的C#6对象初始化程序语法?

[英]New C# 6 object initializer syntax?

I just noticed that the following is possible in C# written in Visual Studio 2015, but I've never seen it before: 我刚刚注意到在Visual Studio 2015中编写的C#中可以使用以下内容,但我以前从未见过它:

public class X
{
    public int A { get; set; }

    public Y B { get; set; }
}

public class Y
{
    public int C {get; set; }
}

public void Foo()
{
    var x = new X { A = 1, B = { C = 3 } };
}

My expectation was for Foo to have to be implemented like this: 我的期望是Foo必须像这样实现:

public void Foo()
{
    var x = new X { A = 1, B = new Y { C = 3 } };
}

Note that there is no need to call new Y . 请注意,无需调用new Y

Is this new in C# 6? 这是C#6中的新功能吗? I haven't seen any mention of this in the release notes , so maybe it's always been there? 我在发行说明中没有看到任何提及,所以也许它一直在那里?

You will get a NullReferenceException if you run this code. 如果运行此代码,您将收到NullReferenceException。

It will not create an instance of Y , it will call the getter of XB property and try to assign value to property C. 它不会创建Y的实例,它将调用XB属性的getter并尝试为属性C赋值。

It always worked like that. 它总是像那样工作。 According to C# 5.0 language specification: 根据C#5.0语言规范:

A member initializer that specifies an object initializer after the equals sign is a nested object initializer, ie an initialization of an embedded object. 在等号后面指定对象初始值设定项的成员初始值设定项是嵌套对象初始值设定项,即嵌入对象的初始化。 Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. 而不是为字段或属性分配新值,嵌套对象初始值设定项中的赋值被视为对字段或属性成员的赋值。

This feature was introduced in C# 3.0 as object initializers. 此功能在C#3.0中作为对象初始化程序引入。

See example on p. 见第2页的例子。 169 of C# Language 3.0 specification : C#语言3.0规范的 169:

Rectangle r = new Rectangle {
    P1 = { X = 0, Y = 1 },
    P2 = { X = 2, Y = 3 }
};

which has the same effect as 效果与...相同

Rectangle __r = new Rectangle();
__r.P1.X = 0;
__r.P1.Y = 1;
__r.P2.X = 2;
__r.P2.Y = 3;
Rectangle r = __r;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM