【问题标题】:C# 8 - CS8605 "Unboxing possibly null value" on enumC# 8 - CS8605“取消装箱可能为空值”枚举
【发布时间】:2020-08-27 18:07:45
【问题描述】:

我在 .csproj 中有一个带有 <nullable>enable</nullable> 的项目 我遇到了一些奇怪的警告行为。

我有一个遍历枚举的 foreach 语句,枚举中的 foreach 项运行一些代码。 但是当我尝试执行此操作时,VS2019 会标记 CS8605“取消装箱可能为空值”警告。

此处显示完整代码。错误显示在t 的减速上。

public static class Textures
{
    private static readonly Dictionary<TextureSet, Texture2D> textureDict = new Dictionary<TextureSet, Texture2D>();

    internal static void LoadContent(ContentManager contentManager)
    {
        foreach(TextureSet t in Enum.GetValues(typeof(TextureSet)))
        {
            textureDict.Add(t, contentManager.Load<Texture2D>(@"textures/" + t.ToString()));
        }
    }

    public static Texture2D Map(TextureSet texture) => textureDict[texture];
}

我很难理解为什么t 有可能为空,因为枚举是不可为空的。 我想知道,由于Enum.GetValues 返回类型为Array,是否有一些隐式转换是这个问题的根源。 我目前的解决方案只是抑制警告。但我想了解这里发生了什么。也许有更好的方法来迭代枚举。

我正在使用 .net Core 3.1 和 Visual Studio Community 2019 16.7.2

【问题讨论】:

标签: c# enums c#-8.0 nullable-reference-types


【解决方案1】:

我在徘徊,因为Enum.GetValues 返回类型为Array 如果有 是这里正在进行的一些隐式转换,这是它的根源 问题。

你是对的,foreach 循环进行了隐式转换。这才是问题的根源。

正如您所注意到的,Enum.GetValues 返回一个 Array 类型的对象。启用nullable context 时,Array 的项目是可空类型object?。当您在 foreach 循环中迭代 Array 时,每个 Array 项目都被强制转换为迭代变量的类型。在您的情况下,object? 类型的每个 Array 项目都被强制转换为 TextureSet 类型。这个演员产生警告Unboxing possibly null value

如果您在sharplab.io 中尝试您的代码,您会看到内部 C# 编译器将考虑的 foreach 循环转换为清楚显示问题的 while 循环(为简单起见,我省略了一些代码块):

IEnumerator enumerator = Enum.GetValues(typeof(TextureSet)).GetEnumerator();
while (enumerator.MoveNext())
{
    // Type of the enumerator.Current is object?, so the next line
    // casts object? to TextureSet. Such cast produces warning
    // CS8605 "Unboxing possibly null value".
    TextureSet t = (TextureSet) enumerator.Current;
}

我目前的解决方案只是抑制警告。 ...也许有更好的方法来迭代枚举。

您也可以使用下一个approach 来修复警告:

foreach (TextureSet t in (TextureSet[]) Enum.GetValues(typeof(TextureSet)))
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2010-11-03
    • 2011-07-19
    • 2012-04-03
    • 1970-01-01
    相关资源
    最近更新 更多