Extension method on enumeration, not instance of enumeration

前端 未结 7 1078
耶瑟儿~
耶瑟儿~ 2020-11-29 04:28

I have an enumeration for my Things like so:

public enum Things
{
   OneThing,
   AnotherThing
}

I would like to write an extension method

相关标签:
7条回答
  • 2020-11-29 05:13

    The closest you can come, I think, is to dummy things up a bit to work like an enum without being one. Here's what I've come up with--it seems like a lot of work just to plop a static method on an enumeration, although I do understand the programming appeal of it:

        public class PseudoEnum
    {
        public const int FirstValue = 1;
        private static PseudoEnum FirstValueObject = new PseudoEnum(1);
    
        public const int SecondValue = 2;
        private static PseudoEnum SecondValueObject = new PseudoEnum(2);
    
        private int intValue;
    
        // This prevents instantation; note that we cannot mark the class static
        private PseudoEnum() {}
    
        private PseudoEnum(int _intValue)
        {
            intValue = _intValue;
        }
    
        public static implicit operator int(PseudoEnum i)
        {
            return i.intValue;
        }
    
        public static implicit operator PseudoEnum(int i)
        {
            switch (i)
            {
                case FirstValue :
                    return FirstValueObject;
                case SecondValue :
                    return SecondValueObject;
                default:
                    throw new InvalidCastException();
            }
        }
    
        public static void DoSomething(PseudoEnum pe)
        {
            switch (pe)
            {
                case PseudoEnum.FirstValue:
                    break;
                case PseudoEnum.SecondValue:
                    break;
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题