C# 接口扩展方法,具有匹配的泛型参数 更新1
我意识到最初对简单泛型类型的限制意味着我无法比较不同类型的对象,无论它们是否实现了C# 接口扩展方法,具有匹配的泛型参数 更新1,c#,generics,extension-methods,C#,Generics,Extension Methods,我意识到最初对简单泛型类型的限制意味着我无法比较不同类型的对象,无论它们是否实现了IComparable,因此最新的是: public static bool IsLessThan<TSource, TComparer>(this TSource source, TComparer comparer) where TSource : IComparable<TComparer> where TComparer : IComparable<TCompa
IComparable
,因此最新的是:
public static bool IsLessThan<TSource, TComparer>(this TSource source, TComparer comparer)
where TSource : IComparable<TComparer>
where TComparer : IComparable<TComparer>
{
return source.CompareTo(comparer) < 0;
}
是否有任何方法可以使用泛型来确保源
和比较器
是相同的类型,同时仍然保持i可比较
的约束
例子
嗯,你可以使用:
public static bool IsLessThan<T>(this T source, T comparer) where T : IComparable
publicstaticbool IsLessThan(这个T源代码,T比较器),其中T:IComparable
或者您可以使用IComparable
,使其更具约束性:
public static bool IsLessThan(此T源、T比较器)
其中T:i可比较
后者在避免装箱方面也更有效。以下是完整的代码
public static class ComparableEx
{
public static bool IsLessThan<T>(this T source, T comparer)
where T : IComparable<T>
{
return source.CompareTo(comparer) < 0;
}
}
class Program
{
static void Main(string[] args)
{
int test = 2;
var resultOne = test.IsLessThan(3); // returns true
var resultTwo = test.IsLessThan("Hello world"); // doesn't compile
}
}
公共静态类可比性
{
公共静态布尔值小于(此T源、T比较器)
其中T:i可比较
{
返回source.CompareTo(比较器)<0;
}
}
班级计划
{
静态void Main(字符串[]参数)
{
int检验=2;
var resultOne=test.IsLessThan(3);//返回true
var resultTwo=test.IsLessThan(“Hello world”);//未编译
}
}
我知道我来晚了,但这是一个独立的解决方案(再加上很难与Jon竞争,叹气……)哈哈,在看到这一点之前试一试,谢谢Jon。我没有意识到将扩展方法放在约束上是足够智能的。。。聪明的小更新;拳击今天成了一个小问题;除了无法与其他类型进行比较之外,无论
IComparable
的实现如何。我已经更新了我的问题以反映我当前的解决方案。您可以对这两个参数使用typeof
,如果它们不相同,则抛出。
public static bool IsLessThan<T>(this T source, T comparer) where T : IComparable
public static bool IsLessThan<T>(this T source, T comparer)
where T : IComparable<T>
public static class ComparableEx
{
public static bool IsLessThan<T>(this T source, T comparer)
where T : IComparable<T>
{
return source.CompareTo(comparer) < 0;
}
}
class Program
{
static void Main(string[] args)
{
int test = 2;
var resultOne = test.IsLessThan(3); // returns true
var resultTwo = test.IsLessThan("Hello world"); // doesn't compile
}
}