1 回答

TA貢獻1873條經(jīng)驗 獲得超9個贊
您的第二個示例聲明了一個變量,但它將為空且無法訪問:
Box b;
int id = b.Id; // Compiler will tell you that you're trying to use a unassigned local variable
我們可以通過用 null 初始化來欺騙編譯器:
Box b = null; // initialize variable with null
try
{
int id = b.Id; // Compiler won't notice that this is empty. An exception will be trown
}
catch (NullReferenceException ex)
{
Console.WriteLine(ex);
}
我們現(xiàn)在看到,我們必須初始化變量才能訪問它:
Box b; // declare an empty variable
b = new Box(); // initialize the variable
int id = b.Id; // now we're allowed to use it.
聲明和初始化的簡短版本是您的第一個示例:
Box b = new Box();
這是我用于示例的示例類:
public class Box
{
public int Id { get; set; }
}
也許您確實注意到Id
我們Box
沒有被初始化。這不是必需的(但大多數(shù)時候您應(yīng)該這樣做),因為它是值類型 ( struct
) 而不是引用類型 ( class
)。
如果您想了解更多信息,請查看以下問題:.NET 中的結(jié)構(gòu)和類有何區(qū)別?
- 1 回答
- 0 關(guān)注
- 109 瀏覽
添加回答
舉報