2016-04-28 22 views
6

我有我的結構:類庫允許使用未分配結構

public struct MyType 
{ 
    private string value; 

    // Methods 
    // ... (ToString overrided too) 
} 

如果我把結構中的Program.cs或其他File.cs,我創建一個變量作爲MyType(我的結構),我嘗試使用它,結果是明顯的錯誤:

CS0165 Use of unassigned local variable

實施例:

MyType a; 
Console.WriteLine(a); // Error: Use of unassigned local variable 'a' 

MyType b = new MyType(); 
Console.WriteLine(b); // Prints the default value (an empty string) 

問題是,當我把結構中的一個類庫(在另一個項目,或者從NuGet包),我用它的Program.cs:

MyType a; 
Console.WriteLine(a); // No error: prints an empty string 

這究竟是爲什麼?

+0

什麼是在第二種情況下的輸出? –

+0

更正了我的答案(完全錯過了班級圖書館的一部分......抱歉)! –

+0

@DmitryK。一個空字符串。添加到問題中。 – Joe

回答

2

據我可以告訴這是設計。在Github上查看此問題:

'error CS0165: Use of unassigned local variable' is not produced for structs with a private reference type field from a different assembly

此問題已被關閉並標記爲「解決方案,通過設計」。

在這一問題上,gafter有這樣一段話:

This was a very painful but intentional decision. This duplicates the (buggy) behavior of the previous compiler. I strongly recommend you add the compiler flag /features:strict to get the correct, specification-required (but not backward-compatible) behavior.

+0

但嚴格模式(必須強制轉換所有變量)和不初始化結構之間存在什麼關係? – Joe

+1

@Joe不知道。從GitHub問題的同一評論中,gafter說:「這目前不在文檔中」,它似乎仍然沒有記錄。 – reduckted

-1

當您從類庫調用Console.WriteLine時,除非您正在運行的項目支持控制檯(命令提示符),否則它將不執行任何操作。在不支持調試的環境中,Debug.WriteLine也是如此。

+0

這不是問題。使用'a.ToString()'也有同樣的問題 - 當類型在本地定義時出現錯誤,但在另一個程序集中定義類型時不存在。 – reduckted