更新1
我意识到简单泛型的原始限制意味着我无法比较不同种类的对象,无论它们是否实现了 IComparable<T>
。或不是,结果现在是最新的:
public static bool IsLessThan<TSource, TComparer>(this TSource source, TComparer comparer)
where TSource : IComparable<TComparer>
where TComparer : IComparable<TComparer>
{
return source.CompareTo(comparer) < 0;
}
原创
我写了一个简单的 IsLessThan(IComparable comparer)
IComparable
上的扩展方法界面。不过,我遇到了一个小问题;我已经意识到基本上它允许任何 IComparable
进行比较,我宁愿没有。或者我想知道是否可以使用泛型来限制参数?目前我的扩展方法是这样的:
public static bool IsLessThan(this IComparable source, IComparable comparer)
{
return source.CompareTo(comparer) < 0;
}
有没有办法使用泛型来确保source
和 comparer
是同一类型,同时仍保持 IComparable
的约束?
例子
int test = 2;
var resultOne = test.IsLessThan(3); // should return true
var resultTwo = test.IsLessThan("Hello world"); // shouldn't compile
最佳答案
好吧,你可以使用:
public static bool IsLessThan<T>(this T source, T comparer) where T : IComparable
或者您可以使用 IComparable<T>
使其更受约束:
public static bool IsLessThan<T>(this T source, T comparer)
where T : IComparable<T>
后者在避免装箱方面也会更有效。
关于c# - 接口(interface)扩展方法,具有匹配的通用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12513833/