简体   繁体   English

C# 如果没有“新”,这个初始化会做什么?

[英]C# What is this initialization doing if it doesn't have the 'new'?

I'm missing what/how this even compiles, and what does it try to do:我错过了它甚至编译的内容/方式,以及它试图做什么:

// 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; }
}

It's obvious that the initialization should include the "new":很明显,初始化应该包括“新”:

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

but how is this compiling even without the "new", and what is it trying to do?但是即使没有“新”,这又是如何编译的,它试图做什么?

Construction建造

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

is a syntactic sugar which is unfurled into是一种语法糖,展开成

Class c2 = new Class2();

c2.C1.Value = "stg"; // <- Here we have the exception thrown

It's not evident for compiler, that C1 is null ( C1 can well be created in the constructor) that's why the code compiles.对于编译器来说, C1null并不明显C1可以在构造函数中创建),这就是代码编译的原因。

Edit: Why compiler allow C1 = { Value = "stg" } ?编辑:为什么编译器允许C1 = { Value = "stg" } It's convenient (syntactic sugar is for our convenience), imagine:这很方便(语法糖是为了我们的方便),想象一下:

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.

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