c# - 为什么空的用户定义结构没有 "Use of unassigned local variable"编译错误?

标签 c#

以下编译成功:

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/

相关文章:

c# - 使用验证覆盖列表中的 .Add 方法

c# - 如何显示数据库 ASP.Net 中的特定行记录?

c# - 创建一个 C# 服务来监视无限循环中的变化

c# - 如何在具有不同where子句的Linq lambda中使用两个条件

c# - Windows Phone 7 Mango 保存 CookieContainer 的状态

C# 遍历并设置结构中的所有字段

c# - 新的空白,非 null 匿名类型

c# - 我的 CSS 文档出现在 Head 中,但没有将任何样式绑定(bind)到元素

C#:将参数传递给回调

c# - XAML - TextTrimming 不适用于 LineBreaks?