How do I overload an operator for an enumeration in C#?

后端 未结 5 1016
南旧
南旧 2020-12-06 04:16

I have an enumerated type that I would like to define the >, <, >=, and <= operators for. I know that these o

5条回答
  •  失恋的感觉
    2020-12-06 04:25

    As other mentioned before, one cannot override operators on Enums, but you can do it on struct. See an example below. Let me know if it helped:

    public struct SizeType
    {
        private int InternalValue { get; set; }
    
        public static readonly int Small = 0;
        public static readonly int Medium = 1;
        public static readonly int Large = 2;
        public static readonly int ExtraLarge = 3;
    
        public override bool Equals(object obj)
        {
            SizeType otherObj = (SizeType)obj;
            return otherObj.InternalValue.Equals(this.InternalValue);
        }
    
        public static bool operator >(SizeType left, SizeType right)
        {
            return (left.InternalValue > right.InternalValue);
        }
    
        public static bool operator <(SizeType left, SizeType right)
        {
            return (left.InternalValue < right.InternalValue);
        }
    
        public static implicit operator SizeType(int otherType)
        {
            return new SizeType
            {
                InternalValue = otherType
            };
        }
    }
    
    public class test11
    {
        void myTest()
        {
            SizeType smallSize = SizeType.Small;
            SizeType largeType = SizeType.Large;
            if (smallSize > largeType)
            {
                Console.WriteLine("small is greater than large");
            }
        }
    }
    

提交回复
热议问题