新的 C# 6 对象初始值设定项语法? [英] New C# 6 object initializer syntax?
问题描述
我刚刚注意到在 Visual Studio 2015 中编写的 C# 中可以实现以下功能,但我以前从未见过它:
I just noticed that the following is possible in C# written in Visual Studio 2015, but I've never seen it before:
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 } };
}
我期望 Foo 必须像这样实现:
My expectation was for Foo to have to be implemented like this:
public void Foo()
{
var x = new X { A = 1, B = new Y { C = 3 } };
}
注意不需要调用new Y
.
这是 C# 6 的新功能吗?我在 中没有看到任何提及发行说明,所以也许它一直在那里?
Is this new in C# 6? I haven't seen any mention of this in the release notes, so maybe it's always been there?
推荐答案
如果您运行此代码,您将收到 NullReferenceException.
You will get a NullReferenceException if you run this code.
它不会创建Y
的实例,它会调用X.B
属性的getter并尝试为属性C赋值.
It will not create an instance of Y
, it will call the getter of X.B
property and try to assign value to property C.
它总是这样工作.根据 C# 5.0 语言规范:
It always worked like that. According to C# 5.0 language specification:
在等号后指定对象初始值设定项的成员初始值设定项是嵌套对象初始值设定项,即嵌入对象的初始化.嵌套对象初始值设定项中的赋值被视为对字段或属性成员的赋值,而不是为字段或属性分配新值.
A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. 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.
这篇关于新的 C# 6 对象初始值设定项语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!