2017-01-23 69 views
4

原始C#值類型,例如int是一個結構。那麼,爲什麼int未初始化?應該有默認的構造函數,我想。另一方面,一個自定義結構是可以的。使用未分配的本地變量:值類型vs自定義結構

在下面的代碼

struct STRCT { } 
class Program 
{ 
    static void Main(string[] args) 
    { 
     STRCT strct; 
     strct.Equals(8); 
     strct.GetHashCode(); 
     strct.GetType(); 
     strct.ToString(); 

     int i; 
     i.Equals(8); 
     i.GetHashCode(); 
     i.GetType(); 
     i.ToString(); 
    } 
} 

而前5行的代碼是從C#編譯器視圖確定,接下來的5行的代碼生成編譯錯誤:

use of unassigned local variable

請解釋爲什麼呢?從我的角度來看,這兩種類型都是結構,並且應該具有相同的行爲。

+1

的http://計算器。com/questions/9233000/why-compile-error-use-of-unassigned-local-variable#answer-9233045請參考上面的鏈接,它會幫助你。 –

回答

8

這是定性分配規則的病態極端。具體做法是:

A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.

在這種情況下(STRCT strct),一組實例變量是空的,所以這是事實,他們都被明確賦值。

+0

我認爲這個問題是爲什麼int未初始化,而不是爲什麼該結構工作 –

+0

@ThomasWeller由於'int'包含一個數據字段不初始化,而空的'結構'做不。 –

+0

@MthetheWWatson:確切地說。這應該是答案的一部分。 –

4

這是因爲,與int不同,您的STRCT不包含任何字段,因此不包含任何可能「未分配」的內容。

嘗試將其更改爲:

struct STRCT 
{ 
    public int X; 
} 

然後你會得到相同的編譯錯誤:

Error CS0165 Use of unassigned local variable 'strct' ConsoleApplication1 D:\Test\CS6\ConsoleApplication1\Program.cs 15

的C#語言規範在第5.3節 「明確賦值」 明確規定:

At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by a particular static flow analysis (§5.3.3), that the variable has been automatically initialized or has been the target of at least one assignment

然後:

A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.

因此,從最後一條規則,如果一個結構沒有實例變量(即,字段),那麼它被認爲是「明確賦值」的,因此不會有編譯錯誤被忽略。

+0

然而,應該有一個錯誤說'strct'變量本身沒有被初始化?不應該有一個'新'行在某處? –

+0

@ThorstenDittmar上面引用的C#規範的部分清楚地說明了爲什麼會發生這種情況。 –

+0

哇!我不知道!所以,我需要做strct.X = 5和它的工作。令人驚訝的,但恕我直言是源的混亂 – zzfima

1

這是類會員自動初始化 - 所以如果你的int是一個字段或類的屬性,你會沒事的。

但是,對方法的局部變量未初始化,並期望您給它們一個值。

由於結構變量不包含它自己的成員,所以暫時可以使用它的結構變量。一旦你添加

struct STRCT 
{ 
    private int a; 
} 

你也會得到一個錯誤。

0

Structsvalue types

Unlike reference types , a value type cannot contain the null value. However, the nullable types feature does allow for value types to be assigned to null. Each value type has an implicit default constructor that initializes the default value of that type. For information about default values of value types

見 - https://msdn.microsoft.com/en-us/library/s1ax56ch.aspx

+0

您應該使用>字符來指示引號。恕我直言,你的文章沒有回答這個問題。 –