簡體   English   中英

C# 如果沒有“新”,這個初始化會做什么?

[英]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

對於編譯器來說, C1null並不明顯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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM