c# - 类库允许使用未分配的结构

标签 c# compiler-errors

我有我的结构:

public struct MyType
{
    private string value;

    // Methods
    // ... (ToString overrided too)
}

如果我将结构放在 Program.cs 或另一个 File.cs 中,并创建一个变量作为 MyType(我的结构)并尝试使用它,结果是一个明显的错误:

CS0165 Use of unassigned local variable

例子:

MyType a; 
Console.WriteLine(a); // Error: Use of unassigned local variable 'a'

MyType b = new MyType(); 
Console.WriteLine(b); // Prints the default value (an empty string)

问题是当我将结构放在类库中(在另一个项目中,或从 NuGet 包中)并从 Program.cs 使用它时:

MyType a;
Console.WriteLine(a); // No error: prints an empty string

为什么会这样?

最佳答案

据我所知这是设计使然。在 GitHub 上查看此问题:

'error CS0165: Use of unassigned local variable' is not produced for structs with a private reference type field from a different assembly

此问题已关闭并标记为“Resolution-By Design”。

在那一期中,gafter有这样的话:

This was a very painful but intentional decision. This duplicates the (buggy) behavior of the previous compiler. I strongly recommend you add the compiler flag /features:strict to get the correct, specification-required (but not backward-compatible) behavior.

关于c# - 类库允许使用未分配的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36903168/

相关文章:

c# - 如何在 WPF C# 中更改 slider 上刻度的设计(刻度的厚度、刻度的形状等...)

c# - 替换此代码中的文字字符串

c# - 在同一个 catch block 中捕获两个异常?

c++ - 在C++中与libmongoclient链接时出错

C++ 无效参数,候选为 : ".." on Setters from different classes

c++ - 我收到链接错误

c++ - GTEST 中 std::map 和 dense_hash_map 的编译器错误

c# - ASP.Net 图表 - 带有未在图表中使用的额外数据的标签?

c# - 如何在一行中检索我有字典 (C#) 的唯一项目的值?

c - 使用 gcc 编译时总线错误