我有一个变量,其值在运行时填充。我想检查该值是否位于两个不同数据类型值(例如最低和最高)之间,或者不使用扩展方法。
这两个值(最低和最高)可以具有相同的数据类型(没问题)。然后就像
public static bool Between<T>(this T actual, T lower, T upper)
where T : IComparable<T>
{
return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) <= 0;
}
感谢我之前提出的问题How to create a Between Extension Method
但是如果它们具有不同的数据类型但具有相同的基类怎么办?
说
我想检查一下
byte a = 2; //here static but is can be changed at runtime
if(a.Between(0,8.0))
DoSomething();
else
DoNothing();
在上面的代码片段中,我正在检查 int 值和 double 值之间的字节值。遇到这种情况该怎么办。我想创建一个扩展方法,例如
public static bool Between<T1, T2, T3>(this T1 actual, T2 lowest, T3 highest)
where T1: ????
where T2: ????
where T3: ????
{
What code to write here????
}
对于上面的代码片段,我的 EM 应该返回 true
最佳答案
刚刚尝试过,我得到的最接近的是:
public static bool Between<T1, T2, T3>(this T1 actual, T2 lowest, T3 highest)
where T1: IComparable
where T2: IConvertible
where T3: IConvertible
{
return actual.CompareTo(lowest.ToType(typeof(T1), null)) >= 0 &&
actual.CompareTo(highest.ToType(typeof(T1), null)) <= 0;
}
这会将 T2
和 T3
转换为 T1
,然后对它们进行比较。
如果 lowest
或 highest
到 T1
类型的转换失败,您将收到异常(例如,如果 T1
code> 是 byte
并且 lower
或 highest
大于 255
)。
因此,您可能需要检查 T1
,并根据需要将 actual
转换为更大的数据类型。
关于c# - 在扩展方法之间创建检查具有相同基类的两个数据类型之间的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512092/