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

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

    How about something like this?

    if (theNumber.isBetween(low, high, IntEx.Bounds.INCLUSIVE_INCLUSIVE))
    {
    }
    

    with the extension method as follows (tested):

    public static class IntEx
    {
        public enum Bounds 
        {
            INCLUSIVE_INCLUSIVE, 
            INCLUSIVE_EXCLUSIVE, 
            EXCLUSIVE_INCLUSIVE, 
            EXCLUSIVE_EXCLUSIVE
        }
    
        public static bool isBetween(this int theNumber, int low, int high, Bounds boundDef)
        {
            bool result;
            switch (boundDef)
            {
                case Bounds.INCLUSIVE_INCLUSIVE:
                    result = ((low <= theNumber) && (theNumber <= high));
                    break;
                case Bounds.INCLUSIVE_EXCLUSIVE:
                    result = ((low <= theNumber) && (theNumber < high));
                    break;
                case Bounds.EXCLUSIVE_INCLUSIVE:
                    result = ((low < theNumber) && (theNumber <= high));
                    break;
                case Bounds.EXCLUSIVE_EXCLUSIVE:
                    result = ((low < theNumber) && (theNumber < high));
                    break;
                default:
                    throw new System.ArgumentException("Invalid boundary definition argument");
            }
            return result;
        }
    }
    

提交回复
热议问题