gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:56:51 25 4
gpt4 key购买 nike

我有我的结构:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com