c# - 嵌套对象初始化语法

标签 c# specifications object-initializers

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

我以前从未见过这种对象初始化。特别是我不明白

InitializedProperty = { UninitializedSubproperty = new MyOtherClass() }

没有任何意义 - 它没有分配任何东西给 InitializedProperty

是否在任何地方指定了此行为?

最佳答案

此语法称为 Object Initialization . C# 规范清楚地给出了很多关于这个主题的例子:

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.

例子是:

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 简化初始化。 Jon Skeet 提供了使用这种语法初始化树状结构的优势的另一种视角。

关于c# - 嵌套对象初始化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16794925/

相关文章:

c# - StyleCop/FxCop 10 - 如何仅在命名空间级别正确抑制消息?

javascript - React Native 中的 Object.keys 顺序

C#:具有两个构造函数的对象:如何限制将哪些属性设置在一起?

powershell - 具有预定义属性的对象实例化

c# - 这个 C# 语法的名称是什么?

c# - 在 foreach 中设置 var 以备后用

c# - 从 Calllog 计算并发调用数

c# - 从全名创建 C# 类型

c# - 如果使用 out 参数,调用范围中的变量何时更改?

c - 是否有一个程序可以作为并行程序正确执行但不能作为顺序程序正确执行?