Compiler Warning (level 1) CS1060

使用了可能未赋值的字段“name”。如果结构未赋值,则结构实例变量在初始化时将不被赋值。

在未进行显式初始化的情况下,结构成员将初始化为其默认值。类类型(及其他引用类型)的默认值为 null。如果在没有对类进行初始化的情况下就尝试访问它,则会在运行时引发 NullReferenceException。编译器无法最终确定类成员是否将进行初始化,因此 CS1060 是警告而不是错误。

更正此错误

  1. 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;

        }
    }  
}

请参阅

结构(C# 编程指南)