1 回答

TA贡献1873条经验 获得超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);
}
我们现在看到,我们必须初始化变量才能访问它:
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
没有被初始化。这不是必需的(但大多数时候您应该这样做),因为它是值类型 ( struct
) 而不是引用类型 ( class
)。
如果您想了解更多信息,请查看以下问题:.NET 中的结构和类有何区别?
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报