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

后端 未结 27 2228
挽巷
挽巷 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:56

    I would do a Range object, something like this:

    public class Range where T : IComparable
    {
        public T InferiorBoundary{get;private set;}
        public T SuperiorBoundary{get;private set;}
    
        public Range(T inferiorBoundary, T superiorBoundary)
        {
            InferiorBoundary = inferiorBoundary;
            SuperiorBoundary = superiorBoundary;
        }
    
        public bool IsWithinBoundaries(T value){
            return InferiorBoundary.CompareTo(value) > 0 && SuperiorBoundary.CompareTo(value) < 0;
        }
    }
    

    Then you use it this way:

    Range myRange = new Range(1,999);
    bool isWithinRange = myRange.IsWithinBoundaries(3);
    

    That way you can reuse it for another type.

提交回复
热议问题