简体   繁体   English

嵌套对象初始值设定项语法

[英]Nested object initializer syntax

Resharper has just suggested the following refactoring to me: Resharper 刚刚向我建议了以下重构:

// Constructor initializes InitializedProperty but
// the UninitializedSubproperty is uninitialized.
var myInstance = new MyClass();
myInstance.InitializedProperty.UninitializedSubproperty = new MyOtherClass();

// becomes

var myInstance = new MyClass
    {
        InitializedProperty = { UninitializedSubproperty = new MyOtherClass() }
    };

I've never seen this kind of object initialization before.我以前从未见过这种对象初始化。 In particular I don't see how特别是我不明白如何

InitializedProperty = { UninitializedSubproperty = new MyOtherClass() }

makes any sense - it's not assigning anything to InitializedProperty .有任何意义 - 它没有为InitializedProperty分配任何东西。

Is this behaviour specified anywhere?此行为是否在任何地方指定?

This syntax is called Object Initialization .这种语法称为 对象初始化 C# specification clearly gives a lot of examples on this subject: C# 规范清楚地给出了很多关于这个主题的例子:

7.6.10.2 Object initializers 7.6.10.2 对象初始值设定项

An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas.对象初始值设定项由一系列成员初始值设定项组成,由 { 和 } 标记括起来并用逗号分隔。 Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and an expression or an object initializer or collection initializer.每个成员初始值设定项都必须命名要初始化的对象的可访问字段或属性,后跟等号和表达式或对象初始值设定项或集合初始值设定项。 It is an error for an object initializer to include more than one member initializer for the same field or property.对象初始值设定项为同一字段或属性包含多个成员初始值设定项是错误的。 It is not possible for the object initializer to refer to the newly created object it is initializing.对象初始值设定项不可能引用它正在初始化的新创建的对象。

Examples are:例子是:

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

Compiles down to:编译为:

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

Having:拥有:

public class Rectangle
{
    public Rectangle()
    {
        P1 = new Point(); //default Point for demo purpose
        P2 = new Point(); //default Point for demo purpose
    }

    public Point P1 { get; set; }
    public Point P2 { get; set; }
}

and

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

Also consider reading a great chapter 8.3 Simplified initialization in C# in depth book.还可以考虑阅读一本很棒的章节8.3 C# 中的简化初始化深入书籍。 Jon Skeet provides another look at advantages of using this kind of syntax for initializing tree-like structures. Jon Skeet 提供了另一种使用这种语法来初始化树状结构的优点。

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

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