使用可能未赋值的字段“name”。 如果未对结构赋值,则结构实例变量最初未赋值。
如果未显式初始化结构成员,则将它们初始化为其默认值。 类类型(和其他引用类型)的默认值为 null。 如果尝试访问类之前,还未初始化类,则将在运行时引发 NullReferenceException
。 编译器无法明确地确定是否会初始化类成员,因此 CS1060 是警告而不是错误。
更正此错误
- 提供
struct
的构造函数,该构造函数初始化其所有成员。
示例
下面的代码生成 CS1060,因为类的类型 U
是 struct S
的成员,但从未进行过初始化。
// 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;
}
}
}