简体   繁体   English

这个C#对象初始化程序代码发生了什么?

[英]What is happening with this C# object initializer code?

What is going on with this C# code? 这个C#代码发生了什么? I'm not even sure why it compiles. 我甚至不确定它为什么编译。 Specifically, what's going on where it's setting Class1Prop attempting to use the object initializer syntax? 具体来说,它在设置Class1Prop尝试使用对象初始化器语法的地方发生了什么? It seems like invalid syntax but it compiles and produces a null reference error at runtime. 它似乎是无效的语法,但它在运行时编译并产生空引用错误。

void Main()
{    
    var foo = new Class1
    {
        Class1Prop = 
        {
            Class2Prop = "one"
        }
    };
}

public class Class1
{
    public Class2 Class1Prop { get; set; }
}

public class Class2
{
    public string Class2Prop { get; set; }
}

This is allowed by object initializer syntax in the C# specification, where it is called a nested object initializer . 这是C#规范中的对象初始化器语法所允许的,它被称为嵌套对象初始化器 It is equivalent to: 它相当于:

var _foo = new Class1();
_foo.Class1Prop.Class2Prop = "one"
var foo = _foo;

It should be a little more obvious why this throws a null reference exception. 为什么抛出空引用异常应该更明显一些。 Class1Prop was never initialized in the constructor of Class1. Class1Prop从未在Class1的构造函数中初始化。

The benefit of this syntax is that the caller can use the convenient object initializer syntax even when the properties are getter-only to set mutable properties on nested objects. 这种语法的好处是调用者可以使用方便的对象初始化器语法,即使属性是getter-only,也只能在嵌套对象上设置可变属性。 For example, if Class1Prop was a getter-only property the example is still valid. 例如,如果Class1Prop是getter-only属性,则该示例仍然有效。

Note that there is an inaccessible temporary variable created to prevent the access of a field or array slot before the full initialization has run. 请注意,创建了一个无法访问的临时变量,以防止在完全初始化运行之前访问字段或数组插槽。

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

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