我有我的结构:
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 上查看此问题:
此问题已关闭并标记为“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/