C# 如果没有 'new',这个初始化在做什么?
C# What is this initialization doing if it doesn't have the 'new'?
我错过了 what/how 这甚至可以编译,它试图做什么:
// 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; }
}
显然初始化应该包括“new”:
var c2 = new Class2 { C1 = new Class1 { Value = "stg" } };
但是即使没有“new”,它是如何编译的,它试图做什么?
施工
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" } };
我错过了 what/how 这甚至可以编译,它试图做什么:
// 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; }
}
显然初始化应该包括“new”:
var c2 = new Class2 { C1 = new Class1 { Value = "stg" } };
但是即使没有“new”,它是如何编译的,它试图做什么?
施工
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" } };