简体   繁体   中英

Return enum type (not instance) in a function, depending on another enum value

I would like a function to give me back enum types depending on another enum's value. Here's a simplified and full of imagery example of what I would like to achieve. This leads to an "is a type but is used like a variable" error.

Is there a way to implement such function ?

Thanks a lot !

public class MyClass
{
    public enum MondayActivities { ... }
    public enum TuesdayActivities { ... }

    public Enum PossibleActivitiesByDay(DayEnum day)
    {
        switch (day)
        {
            case DayEnum.Monday:
                return MondayActivities ;
            case DayEnum.Tuesday:
                return TuesdayActivities ;
            ...
        }
    }
}

Yes, there is a way to do it, but you're not going to like it because the values you get back are going to be more-or-less useless! You wont know what they are.

public enum DayEnum{Monday,Tuesday}
public enum MondayActivities { Washing, Ironing }
public enum TuesdayActivities { Cleaning, Hoovering }

public static Array PossibleActivitiesByDay(DayEnum day)
{
    switch (day)
    {
        case DayEnum.Monday:
            return Enum.GetValues(typeof(MondayActivities)) ;
        case DayEnum.Tuesday:
            return Enum.GetValues(typeof(TuesdayActivities )) ;
    }
    return null;
 }

Usage:

foreach(var value in PossibleActivitiesByDay(DayEnum.Monday))
{
    Console.WriteLine(value);
}

Live example: http://rextester.com/CTUBYA10553

That works, as you can see, in that it prints the name of the returned values, but programatically you have no type-safety - you dont know if its a MondayActivity or a TuesdayActivity .

The answer is pretty much already in your question. Just return wanted enum's type, not value or general-purpose Enum.

public Type PossibleActivitiesByDay(DayEnum day)
{
    switch (day)
    {
        case DayEnum.Monday:
            return typeof(MondayActivities) ;
        case DayEnum.Tuesday:
            return typeof(TuesdayActivities) ;
        ...
    }
}

Even if Enum is a type inside CLR , it does not support polymorphism, so you can not abstract it over some hypothetical "base" enum .

The only reasonable solution, I'm afraid, in presented case is to define distinct functions that return concrete enum types.

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