[英]Best way to compare two generic values?
I'm writing a small class which I'm gonna move around when needed like a dll, and it's gonna have different sorting algorithms in it. 我正在编写一个小类,可以在需要时像dll一样四处移动,并且其中将包含不同的排序算法。 I want the functions to work with any lists, of any types, including objects.
我希望这些功能可与任何类型的任何列表(包括对象)一起使用。 So it's basically like this:
所以基本上是这样的:
class TemplateSortings<T>
{
List<T> GNRList;
static void SortBubble<T>()
{
//Do stuff with GNRList, which can be a list of any values (nums, strings, objects)
}
}
Now the question I'm having troubles with is this - what is the best way to compare two generic values: overloading comparison operators or having the class inherit IComparable interface? 现在,我遇到的问题是-比较两个通用值的最佳方法是什么:重载比较运算符或让类继承IComparable接口? What is better and why?
有什么更好的,为什么?
If you want it to work with any type, you probably shouldn't constrain T
to types that implement IComparable
, because not all types do. 如果您希望它与任何类型一起使用,则可能不应该将
T
限制为实现IComparable
类型,因为并非所有类型都可以。
A simple way to work around this is to let the caller decide how to compare the objects. 解决此问题的一种简单方法是让调用方决定如何比较对象。 You just need an extra parameter:
您只需要一个额外的参数:
static void SortBubble(Func<T, T, int> comparator)
{
...
}
You can call comparator
with 2 arguments and it will give you a negative value, 0, or a positive value indicating that the first parameter is less than, equal to, or greater than the second parameter. 您可以使用2个参数调用
comparator
,它将给出一个负值,0或一个正值,指示第一个参数小于,等于或大于第二个参数。
As an example, you can call SortBubble
with int
s like this: 例如,您可以使用
int
调用SortBubble
,如下所示:
var sorting = new TemplateSortings<int>();
// populate the list...
sorting.SortBubble((x, y) => x.CompareTo(y)) // pass a lambda
EDIT: 编辑:
If you don't want an extra parameter and want to check the type inside the method, you can do something like this: 如果您不需要额外的参数并且想要检查方法内部的类型,则可以执行以下操作:
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T))) {
// do your sorting
// you need to cast values of type "T" to "Comparable<T>" like this
// var castedValue = (IComparable<T>)tValue;
} else {
throw ...
}
You could generalize your code so it can work with any potentially valid type T
: 您可以泛化您的代码,使其可以与任何可能有效的类型
T
:
public static IEnumerable<T> BubbleSort(
this IEnumerable<T> source,
IComparer<T> comparer == null)
{
var currentComparer = comparer ?? Comparer<T>.Default;
//bubble sort with currentComparator
}
Now, you can sort any T
whatsoever, if: 现在,您可以对任何
T
进行排序,如果:
T
implements IComparable<T>
T
实现IComparable<T>
T
implements legacy IComparable
T
实现传统的IComparable
Comparator
that knows how to compare T
s Comparator
,知道如何比较T
小号 It will fail on any other scenario the moment you attempt to perform the first comparison. 当您尝试执行第一次比较时,它将在任何其他情况下失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.