はじめに
前回の Between()
は、上限値と下限値をそれぞれ「含む」「含まない」を選択することができませんでした。今回、できるものをつくってみました。
しかし、ちょっと重厚長大になりすぎる嫌いがあるので、有用ではないかもしれません。
サンプルコード
using System;
namespace BetweenTest
{
class EndPoint<T>
{
public enum OperatorType
{
Including,
Excluding
}
public T Value { get; set; }
public OperatorType Operator { get; private set; }
public EndPoint(T t) { Value = t; }
public static EndPoint<T> Including(T val)
{
return new EndPoint<T>(val)
{
Operator = OperatorType.Including
};
}
public static EndPoint<T> Excluding(T val)
{
return new EndPoint<T>(val)
{
Operator = OperatorType.Excluding
};
}
}
static class Ext
{
public static bool Between<T>(this T source, T low, T high) where T : IComparable
{
if (low.CompareTo(high) > 0) { throw new ArgumentException(); }
return source.CompareTo(low) >= 0 && source.CompareTo(high) <= 0;
}
public static bool Between<T>(this T source, EndPoint<T> low, EndPoint<T> high) where T : IComparable
{
if (low.Value.CompareTo(high.Value) > 0) { throw new ArgumentException(); }
bool validLow;
if (low.Operator == EndPoint<T>.OperatorType.Including)
{
validLow = source.CompareTo(low.Value) >= 0;
}
else
{
validLow = source.CompareTo(low.Value) > 0;
}
bool validHigh;
if (high.Operator == EndPoint<T>.OperatorType.Including)
{
validHigh = source.CompareTo(high.Value) <= 0;
}
else
{
validHigh = source.CompareTo(high.Value) < 0;
}
return validLow && validHigh;
}
}
class Program
{
static void Main(string[] args)
{
if (5.Between(1, 6))
{
Console.WriteLine("Hello World!");
}
if ("5".Between("0", "9"))
{
Console.WriteLine("Hello World!");
}
var validRangeFrom = EndPoint<int>.Excluding(0);
var validRangeLimit = EndPoint<int>.Including(5);
if (5.Between(validRangeFrom, validRangeLimit))
{
Console.WriteLine("Hello World!");
}
}
}
}