gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:16:32 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com