开发者

C# Enum Indexing Question

Is it possible to use an index integer to obtain an enum value? For example, if...

public enum Days {开发者_运维技巧 Mon, Tues, Wed, ..., Sun};

...is it somehow possible to write something like...

Days currentDay = Days[index];

Thanks!


No, but you can cast an int to an enum, if the value you are using is defined in the enum, however you do this at your own risk:

Days currentDay = (Days)index;

If you really want to be safe, you can check if it's defined first, but that will involve some boxing, etc and will damper performance.

// checks to see if a const exists with the given value.
if (Enum.IsDefined(typeof(Days), index))
{
    currentDay = (Days)index;
}

If you know your enum is a specified, contiguous value range (i.e. Mon = 0 thru Sun = 6) you can compare:

if (index >= (int)Days.Mon && index <= (int)Days.Sun)
{
    currentDay = (Days) index;
}

You can also use the array passed back by Enum.GetValues(), but once again this is heavier than the cast:

Day = (Day)Enum.GetValues(typeof(Day))[index];


If you index your enums properly, you can just case the int (or whatever index is) to the enum.

So...

public enum Days { Mon = 0, Tue, Wed .... }

Days today = (Days)1;    


I had to do some calculations with the DaysOfWeek enum before. I used an extension method to create a safe default.

Here's an example:

public enum Days { Invalid = ~0, Mon, Tues, Wed, Thurs, Fri, Sat, Sun };
class Program
{
    static void Main(string[] args)
    {
        int day = 8;
        Days day8 = (Days)day;
        Console.WriteLine("The eighth day is {0}", day8);

        Console.WriteLine("Days contains {0}: {1}", 
            day, Enum.IsDefined(typeof(Days), day));

        Console.WriteLine("Invalid day if {0} doesn't exist: {1}", 
            day, day8.OrDefault(Days.Invalid) );

        Console.WriteLine("Sunday day if {0} doesn't exist: {1}", 
            day, day8.OrDefault(Days.Sun));

        Days day9 = ((Days)9).OrDefault(Days.Wed);
        Console.WriteLine("Day (9) defaulted: {1}", 9, day9);

        Console.ReadLine();
    }
}
public static class DaysExtensions
{
    public static Days OrDefault(this Days d, Days defaultDay) 
    {
        if (Enum.IsDefined(typeof(Days), (Days)d))
        {
            return d;
        }

        return defaultDay;
    }
}

And the output:

The eighth day is 8
Days contains 8: False
Invalid day if 8 doesn't exist: Invalid
Sunday day if 8 doesn't exist: Sun
Day (9) defaulted: Wed
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜