我有这行C#代码:
var __allFlags = Enum.Parse(enumType, allFlags);
Run Code Online (Sandbox Code Playgroud)
它抛出了一个InvalidCastException,我不知道为什么-如果设置一个断点并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"));
}
Run Code Online (Sandbox Code Playgroud)
这是被测试的方法:
/// <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);
}
Run Code Online (Sandbox Code Playgroud)
以防万一,这里是用于测试的枚举:
/// <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
}
Run Code Online (Sandbox Code Playgroud)
我怀疑问题出在您的按位比较中:
return (((int)__allFlags & (int)__singleFlag) == (int)__singleFlag);
Run Code Online (Sandbox Code Playgroud)
因为在任何情况下Enum.Parse都不会抛出异常InvalidCastException,并且返回一个object类型。
作为调试步骤,注释掉该行并将其替换为return true;暂时的,然后运行测试以查看是否引发异常。Parse如果不是,您可能需要在转换为 之前在前面的行中显式转换为枚举类型int。