Enum “Inheritance”

后端 未结 15 1497
野性不改
野性不改 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 07:55

    The short answer is no. You can play a bit, if you want:

    You can always do something like this:

    private enum Base
    {
        A,
        B,
        C
    }
    
    private enum Consume
    {
        A = Base.A,
        B = Base.B,
        C = Base.C,
        D,
        E
    }
    

    But, it doesn't work all that great because Base.A != Consume.A

    You can always do something like this, though:

    public static class Extensions
    {
        public static T As(this Consume c) where T : struct
        {
            return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
        }
    }
    

    In order to cross between Base and Consume...

    You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.

    The extension method return should type cast it type T.

提交回复
热议问题