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

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

    With a bit of extension method abuse, we can get the following "elegant" solution:

    using System;
    
    namespace Elegant {
        public class Range {
            public int Lower { get; set; }
            public int Upper { get; set; }
        }
    
        public static class Ext {
            public static Range To(this int lower, int upper) {
                return new Range { Lower = lower, Upper = upper };
            }
    
            public static bool In(this int n, Range r) {
                return n >= r.Lower && n <= r.Upper;
            }
        }
    
        class Program {
            static void Main() {
                int x = 55;
                if (x.In(1.To(100)))
                    Console.WriteLine("it's in range! elegantly!");
            }
        }
    }
    

提交回复
热议问题