[英]C# What is this initialization doing if it doesn't have the '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" } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.