我有一行 C# 代码:
var __allFlags = Enum.Parse(enumType, allFlags);
它抛出了一个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"));
}
这里是正在测试的方法:
/// <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
}
allFlags
值的位置。 - Pedro