以下编译成功:
struct Foo {}
void Test()
{
Foo foo;
foo.ToString();
}
而以下会产生“使用未分配的局部变量”编译错误。
struct Foo
{
int i;
}
void Test()
{
Foo foo;
foo.ToString();
}
在第一种情况下,编译器似乎做出了某种推断,即由于该结构没有成员,因此不需要对其进行初始化。但我不确定这对我是否有意义。编译器可能会强制您将 foo
变量初始化为 new Foo()
。
那么,如果在 C# 中所有局部变量都必须在访问之前进行初始化,为什么第一个示例可以编译?
最佳答案
C# 5 规范的第 5.3 节介绍了这一点:
A struct-type variable is considered definitely assigned if each of its instance variables is considered definitely assigned.
当没有实例变量时会自动出现这种情况,因此该变量被认为是明确分配的,并且可以在 ToString()
调用中使用。
关于c# - 为什么空的用户定义结构没有 "Use of unassigned local variable"编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530908/