[英]How to remove compiler error with struct: “Use of unassigned local variable”
[英]compiler showing different errors for unassigned struct object field and property
在第 1 行的以下代碼中,編譯器顯示錯誤:“使用可能未分配的字段 'IntField'”,但對於第 2 行,錯誤是“使用可能未分配的局部變量 'structObj'”。 為什么不同的錯誤?
class Program
{
static void Main(string[] args)
{
StructA structObj;
Console.WriteLine(structObj.IntField); //Line :1
Console.WriteLine(structObj.IntProperty); //Line :2
Console.ReadKey();
}
}
struct StructA
{
public int IntField;
public int IntProperty { get; set; }
}
因為StructA
是一個結構體,而IntField
是一個字段。
在使用之前嘗試StructA structObj = new StructA()
。
我認為錯誤之間差異的原因是屬性轉換為方法。 並且不可能在未初始化的對象上調用方法。
這里需要為結構調用 new() ,因為如果不使用 New 運算符,則字段保持未分配狀態,並且在所有字段初始化之前無法使用對象。
所以對於財產價值的初始化,它必須是
StructA structObj = new StructA();
您可以嘗試不使用 new 僅用於結構中的變量,但需要初始化,因此只需分配值
structObj.IntField= 1;
但是對於財產,您需要 new()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.