Enum “Inheritance”

后端 未结 15 1721
野性不改
野性不改 2020-11-22 07:21

I have an enum in a low level namespace. I\'d like to provide a class or enum in a mid level namespace that \"inherits\" the low level enum.

namespace low
{
         


        
15条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:14

    I realize I'm a bit late to this party, but here's my two cents.

    We're all clear that Enum inheritance is not supported by the framework. Some very interesting workarounds have been suggested in this thread, but none of them felt quite like what I was looking for, so I had a go at it myself.

    Introducing: ObjectEnum

    You can check the code and documentation here: https://github.com/dimi3tron/ObjectEnum.

    And the package here: https://www.nuget.org/packages/ObjectEnum

    Or just install it: Install-Package ObjectEnum

    In short, ObjectEnum acts as a wrapper for any enum. By overriding the GetDefinedValues() in subclasses, one can specify which enum values are valid for this specific class.

    A number of operator overloads have been added to make an ObjectEnum instance behave as if it were an instance of the underlying enum, keeping in mind the defined value restrictions. This means you can easily compare the instance to an int or enum value, and thus use it in a switch case or any other conditional.

    I'd like to refer to the github repo mentioned above for examples and further info.

    I hope you find this useful. Feel free to comment or open an issue on github for further thoughts or comments.

    Here are a few short examples of what you can do with ObjectEnum:

    var sunday = new WorkDay(DayOfWeek.Sunday); //throws exception
    var monday = new WorkDay(DayOfWeek.Monday); //works fine
    var label = $"{monday} is day {(int)monday}." //produces: "Monday is day 1."
    var mondayIsAlwaysMonday = monday == DayOfWeek.Monday; //true, sorry...
    
    var friday = new WorkDay(DayOfWeek.Friday);
    
    switch((DayOfWeek)friday){
        case DayOfWeek.Monday:
            //do something monday related
            break;
            /*...*/
        case DayOfWeek.Friday:
            //do something friday related
            break;
    }
    

提交回复
热议问题