gpt4 book ai didi

c# - Enum.Parse 抛出 InvalidCastException

转载 作者:太空狗 更新时间:2023-10-29 23:35:56 24 4
gpt4 key购买 nike

我有这行 C# 代码:

var __allFlags = Enum.Parse(enumType, allFlags);

它抛出一个 InvalidCastException,我不知道为什么 - 如果我设置一个断点并在监 window 口中运行 Enum.Parse(enumType, allFlags) ,我得到了预期的结果而不是错误。

enumType 设置为 typeof(PixelColor),其中 PixelColor 是我用于单元测试目的的枚举,而 allFlags 设置为字符串 "Red",它是 PixelColor 的可能值之一。

编辑:这是我的单元测试:

[TestMethod]
public void IsFlagSetStringTest()
{
Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), "Red", "Red"));
Assert.IsFalse(EnumHelper.IsFlagSet(typeof(PixelColor), "Red", "Green"));
Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), "White", "Red"));
Assert.IsTrue(EnumHelper.IsFlagSet(typeof(PixelColor), "White", "Red, Green"));
Assert.IsFalse(EnumHelper.IsFlagSet(typeof(PixelColor), "Red", "Red, Green"));
}

这是正在测试的方法:

/// <summary>
/// Determines whether a single flag value is specified on an enumeration.
/// </summary>
/// <param name="enumType">The enumeration <see cref="Type"/>.</param>
/// <param name="allFlags">The string value containing all flags.</param>
/// <param name="singleFlag">The single string value to check.</param>
/// <returns>A <see cref="System.Boolean"/> indicating that a single flag value is specified for an enumeration.</returns>
public static bool IsFlagSet(Type enumType, string allFlags, string singleFlag)
{
// retrieve the flags enumeration value
var __allFlags = Enum.Parse(enumType, allFlags);
// retrieve the single flag value
var __singleFlag = Enum.Parse(enumType, singleFlag);

// perform bit-wise comparison to see if the single flag is specified
return (((int)__allFlags & (int)__singleFlag) == (int)__singleFlag);
}

为了以防万一,这里是用于测试的枚举:

/// <summary>
/// A simple flags enum to use for testing.
/// </summary>
[Flags]
private enum PixelColor
{
Black = 0,
Red = 1,
Green = 2,
Blue = 4,
White = Red | Green | Blue
}

最佳答案

我怀疑问题出在您的按位比较中:

return (((int)__allFlags & (int)__singleFlag) == (int)__singleFlag);

因为 Enum.Parse 在任何情况下都不会抛出 InvalidCastException,并且会返回一个 object 类型。

作为调试步骤,注释该行并暂时将其替换为 return true;,然后运行测试以查看是否抛出异常。如果不是,您可能需要在转换为 int 之前在前面的 Parse 行中显式转换为枚举类型。

关于c# - Enum.Parse 抛出 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57117690/

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