嵌套对象初始化语法 [英] Nested object initializer syntax

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

问题描述

ReSharper的刚刚提出以下重构对我说:

Resharper has just suggested the following refactoring to me:

// 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() }

让任何意义 - 它不是的分配的任何 InitializedProperty

时的地方指定这种行为?

Is this behaviour specified anywhere?

推荐答案

本语法称为​​对象初始化。 C#规范明确给出了很多的例子对这个问题:

This syntax is called Object Initialization. C# specification clearly gives a lot of examples on this subject:

这是对象初始化
  由成员初始化序列的,由封闭{和}
  令牌和用逗号分隔。每个成员初始化必须命名
  访问字段或对象的属性被初始化,随后
  一个等号和一个前pression或对象初始化或
  集合初始化。这是一个对象初始化一个错误
  包括多个成员初始化为同一字段或
  属性。这是不可能的对象初始指
  新创建的对象被初始化。

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.

的实例是:

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

编译为:

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

有:

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

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

也可以考虑读 C#深度图书伟大篇章的 8.3简化初始化的。乔恩斯基特提供了另一个看看使用这种句法的初始化树状结构的优点。

Also consider reading a great chapter 8.3 Simplified initialization in C# in depth book. Jon Skeet provides another look at advantages of using this kind of syntax for initializing tree-like structures.

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

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