編譯器警告 (層級 1) CS1060
更新:2007 年 11 月
錯誤訊息
使用可能為未指派的欄位 'name'。如果未指派結構,則初始時不會指派結構執行個體變數。
如果未明確初始化結構成員,則會將結構 (Struct) 成員初始化為它們的預設值。類別 (Class) 型別 (和其他參考型別) 的預設值是 null。如果還沒有初始化類別就嘗試對其進行存取,則會在執行階段擲回 NullReferenceException。最後,編譯器會無法判斷是否初始化類別成員,因此 CS1060 是警告,而不是錯誤。
若要更正這個錯誤
- 提供初始化其所有成員之 struct 的建構函式 (Constructor)。
範例
因為類別型別 U 是 struct S 的成員,但永遠不會進行初始化,所以下列程式碼會產生 CS1060。
// cs1060.cs
namespace CS1060
{
public class U
{
public int i;
}
public struct S
{
public U u;
// Add constructor to correct the error.
//public S(int val)
//{
// u = new U() { i = val };
//}
}
public class Test
{
static void Main()
{
S s;
s.u.i = 5; // CS1060
//Try these lines instead, and uncomment the constructor in S
// S s = new S(0);
// s.u.i = 5;
}
}
}