本文介绍了比较器< T> .NET 4中的创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在.Net 4.5中创建了一个比较器:
I have created a Comparer in .Net 4.5:
public static Comparer<Room> RoomComparer =
Comparer<Room>.Create((a, b) => a.RoomId.CompareTo(b.RoomId))
如何在c#.NET 4.0中创建比较器?
How can i create Comparer in c# .NET 4.0?
推荐答案
您可以使用以下
public static class Comparer
{
public static Comparer<T> Create<T>(Comparison<T> comparison)
{
if (comparison == null) throw new ArgumentNullException("comparison");
return new ComparisonComparer<T>(comparison);
}
private sealed class ComparisonComparer<T> : Comparer<T>
{
private readonly Comparison<T> comparison;
public ComparisonComparer(Comparison<T> comparison)
{
this.comparison = comparison;
}
public override int Compare(T x, T y)
{
return comparison(x, y);
}
}
}
像这样
public static Comparer<Room> RoomComparer =
Comparer.Create<Room>((a, b) => a.RoomId.CompareTo(b.RoomId))
这篇关于比较器< T> .NET 4中的创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!