简体   繁体   中英

Enum.Parse throws InvalidCastException

I have this line of C# code:

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

It is throwing an InvalidCastException and I can't figure out why - if I set a breakpoint and run Enum.Parse(enumType, allFlags) in the watch window, I get the expected result and not an error.

enumType is set to typeof(PixelColor) where PixelColor is an enum I am using for unit testing purposes, and allFlags is set to the string "Red" which is one of the possible values of PixelColor .

edit: here is my unit test:

[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"));
}

and here is the method being tested:

/// <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);
}

and just in case, here is the enum used for testing:

/// <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
}

I suspect the issue is in your bitwise comparison:

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

Since Enum.Parse does not throw an InvalidCastException in any scenario, and is returning an object type.

As a debugging step, comment that line out and replace it with return true; temporarily, then run the test to see if exception is thrown. If not, you may need to explicitly cast to the enum type on the prior Parse lines before casting to int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM