扩展方法是什么?
bool Between(this int value, int left, int right)
{
return value > left && value < right;
}
if(x.Between(4199, 6800) || x.Between(6999, 8200) || ...)
你也可以使用这种可怕的hack方法:
bool Between(this int value, params int[] values)
{
// Should be even number of items
Debug.Assert(values.Length % 2 == 0);
for(int i = 0; i < values.Length; i += 2)
if(!value.Between(values[i], values[i + 1])
return false;
return true;
}
if(x.Between(4199, 6800, 6999, 8200, ...)
可怕的 hack,改良版:
class Range
{
int Left { get; set; }
int Right { get; set; }
}
Range R(int left, int right)
{
return new Range(left, right)
}
bool Between(this int value, params Range[] ranges)
{
for(int i = 0; i < ranges.Length; ++i)
if(value > ranges[i].Left && value < ranges[i].Right)
return true;
return false;
}
if(x.Between(R(4199, 6800), R(6999, 8200), ...))
或者,更好的方法是(这不允许重复的下限):
bool Between(this int value, Dictionary<int, int> ranges)
{
}
if(x.Between({ { 4199, 6800 }, { 6999, 8200 }, ... }
if ( 0 < x && x < 10)
。 - Dick de Reus