Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用嵌套对象时对象初始值设定项中的指定顺序_C#_Object Initializers - Fatal编程技术网

C# 使用嵌套对象时对象初始值设定项中的指定顺序

C# 使用嵌套对象时对象初始值设定项中的指定顺序,c#,object-initializers,C#,Object Initializers,我有以下代码使用对象初始值设定项创建Root的实例: var r = new Root { Person = new Person { Age = 20, Name = "Hans" } }; public class Point { int x, y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } }

我有以下代码使用对象初始值设定项创建
Root
的实例:

var r = new Root { Person = new Person { Age = 20, Name = "Hans" } };
public class Point
{
    int x, y;
    public int X { get { return x; } set { x = value; } }
    public int Y { get { return y; } set { y = value; } }
}

public class Rectangle
{
    Point p1, p2;
    public Point P1 { get { return p1; } set { p1 = value; } }
    public Point P2 { get { return p2; } set { p2 = value; } }
}

Rectangle r = new Rectangle 
{
    P1 = new Point { X = 0, Y = 1 },
    P2 = new Point { X = 2, Y = 3 }
};
从我知道,如果我们只有内部对象
Person
,这被翻译成这样的东西:

var p = new Person();
p.Age = 20;
p.Name = 20;
var r = new Root();
r.Person = new Person();
r.Person.Age = 20;          // this would call the Persons getter
r.Person.Name = "Hans";     // this would call the Persons getter
我想知道的是,在我的第一个示例中,这是如何影响嵌套对象的?
Person
是否已完全创建并分配给
Root
的新实例,或者仅将其转换为如下内容:

var p = new Person();
p.Age = 20;
p.Name = 20;
var r = new Root();
r.Person = new Person();
r.Person.Age = 20;          // this would call the Persons getter
r.Person.Name = "Hans";     // this would call the Persons getter

我询问的原因是,为给定的
修改
Person
的getter和setter非常复杂,我希望避免为了设置该
Person

的属性而调用其getter,我们可以通过在getter中为
Person
设置断点来轻松检查这一点
根目录
-类。调试时,我们注意到它从未命中

这确实会导致创建以下对象图:

var p = new Person();
p.Age = 20;
p.Name = "Hans";

var r = new Root();
r.Person = p;
您可以看到,没有访问getter来设置persons属性,因为
Person
是在任何
之前首先创建的


这确保了只有在先前已完全创建了
人员的情况下才能完全创建
根目录

这在C语言规范的7.6.10.2中有明确说明

本标准给出了“嵌套对象初始值设定项”的示例:

该标准规定,这与:

Rectangle __r = new Rectangle();
Point __p1 = new Point();
__p1.X = 0;
__p1.Y = 1;
__r.P1 = __p1;
Point __p2 = new Point();
__p2.X = 2;
__p2.Y = 3;
__r.P2 = __p2; 
Rectangle r = __r;
在这里,您可以看到
Rectangle.P1
Rectangle.P2
属性是从已经创建的
对象初始化的

这证明你的问题的答案是正确的

Person是否已完全创建并分配给Root的新实例

肯定是:是的