C# 如果此初始化没有"new",它在做什么?



我不知道它是如何编译的,以及它试图做什么:

// throws null reference exception on 'get' for C1:
var c2 = new Class2 { C1 = { Value = "stg" } };
public class Class1
{
public string Value { get; set; }
}
class Class2
{
public Class1 C1 { get; set; }
}

很明显,初始化应该包括";新的":

var c2 = new Class2 { C1 = new Class1 { Value = "stg" } };

但是,即使没有";新的";,它想做什么?

建筑

var c2 = new Class2 { C1 = { Value = "stg" } }; 

是一种句法糖,它被展开为

Class c2 = new Class2();
c2.C1.Value = "stg"; // <- Here we have the exception thrown

对于编译器来说,C1就是null(C1可以在构造函数中创建(这一点并不明显,这就是代码编译的原因。

编辑:为什么编译器允许C1 = { Value = "stg" }?这很方便(语法糖是为了我们的方便(,想象一下:

public class Class1 {
public string Value { get; set; }
}
class Class2 {
// Suppose, that in 99% cases we want C1 with Value == "abc"
// But only when Class1 instance is a property C1 of Class2
public Class1 C1 { get; set; } = new Class1() { Value = "abc" };
}
...
// however, in our particular case we should use "stg":
var c2 = new Class2 { C1 = { Value = "stg" } };
// for some reason I recreate C1 (note "new"):
var otherC2 = new Class2 { C1 = new Class1 { Value = "stg" } };

相关内容

最新更新