How to elegantly check if a number is within a range?

后端 未结 27 2114
挽巷
挽巷 2020-11-27 11:17

How can I do this elegantly with C# and .NET 3.5/4?

For example, a number can be between 1 and 100.

I know a simple if would suffice; but the keyword to this

27条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 11:38

    These are some Extension methods that can help

      public static bool IsInRange(this T value, T min, T max)
    where T : System.IComparable
        {
            return value.IsGreaterThenOrEqualTo(min) && value.IsLessThenOrEqualTo(max);
        }
    
    
        public static bool IsLessThenOrEqualTo(this T value, T other)
             where T : System.IComparable
        {
            var result = value.CompareTo(other);
            return result == -1 || result == 0;
        }
    
    
        public static bool IsGreaterThenOrEqualTo(this T value, T other)
             where T : System.IComparable
        {
            var result = value.CompareTo(other);
            return result == 1 || result == 0;
        }
    

提交回复
热议问题