开发者

Why can I parse invalid values to an Enum in .NET?

Why is this even possible? Is it a bug?

using System;

public class InvalidEnumParse
{
    public enum Number
    {
        One,
        Two,
        Three,
        Four
    }

    public static void Main()
    {
        string input = "761";
        Number number = (Number)Enum.Parse(typeof(Number), input);
        Console.WriteLine(number); //outputs 761
   开发者_JAVA百科 }
}


That's just the way enums work in .NET. The enum isn't a restrictive set of values, it's really just a set of names for numbers (and a type to collect those names together) - and I agree that's a pain sometimes.

If you want to test whether a value is really defined in the enum, you can use Enum.IsDefined after parsing it. If you want to do this in a more type-safe manner, you might want to look at my Unconstrained Melody project which contains a bunch of constrained generic methods.


If you have a enum with [Flags] attribute, you can have any value combination. For instance:

[Flags]
enum Test
{
    A = 1, 
    B = 2,
    C = 4,
    D = 8
}

You could to do this:

Test sample = (Test)7;
foreach (Test test in Enum.GetValues(typeof(Test)))
{
    Console.WriteLine("Sample does{0} contains {1}",
        (sample & test) == test ? "": " not", test);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜