c# - 类比较器: IComparer.Compare 的显式实现存在的目的
问题描述
IComparer.Compare 的显式实现存在于Comparer<T>
类的实现中的目的。如果我实现了public abstract int Compare (T x, T y)
可能使用的调用的原因和位置int IComparer.Compare (object ObjX, object ObjY)
,考虑到必须可以将 ObjX 和 ObjY 强制转换为类型 T(在其他情况下将是 ArgumentException)。
第 12 行和第 13 行将产生相同的动作;
class Program
{
static void Main(string[] args)
{
IComparer iRefCommon = (IComparer)new BoxLengthFirst();
object obj1 = new Box(2, 6, 8);
object obj2 = new Box(10, 12, 14);
int resulCompare = iRefCommon.Compare((Box)obj1, (Box)obj2); //line12
resulCompare = (new BoxLengthFirst()).Compare(new Box(2, 6, 8),
new Box(10, 12, 14)); //line13
}
}
public class BoxLengthFirst : Comparer<Box>
{
public override int Compare(Box x, Box y)
{
if (x.Length.CompareTo(y.Length) != 0)
{
return x.Length.CompareTo(y.Length);
}
.....
else
{
return 0;
}
}
}
public class Box : IComparable, IComparable<Box>
{
public Box(int h, int l, int w)
{
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; private set; }
public int Length { get; private set; }
public int Width { get; private set; }
public int CompareTo(object obj)
{
....
}
public int CompareTo(Box other)
{
....
}
}
解决方案
尝试以下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication108
{
class Program
{
static void Main(string[] args)
{
Box a = new Box(1, 1, 1);
Box b = new Box(2, 2, 2);
int c = a.CompareTo(b);
}
}
public class Box : IComparable
{
public Box() { }
public Box(int h, int l, int w)
{
this.Height = h;
this.Length = l;
this.Width = w;
}
public int Height { get; private set; }
public int Length { get; private set; }
public int Width { get; private set; }
public int CompareTo(object obj)
{
return CompareTo((Box)obj);
}
public int CompareTo(object obj1, object obj2)
{
return ((Box)obj1).CompareTo((Box)obj2);
}
public int CompareTo(Box other)
{
int results = this.Height.CompareTo(other.Height);
if (results != 0)
{
results = this.Length.CompareTo(other.Length);
if (results != 0)
{
results = this.Width.CompareTo(other.Width);
}
}
return results;
}
}
}
推荐阅读
- wpf - 如何在 WPF 应用程序中获取 ListViewItem 的值和文本颜色?
- php - 用 PHP 分组数组结构
- google-cloud-platform - 以编程方式检查 Google Play 控制台统计报告是否已更新
- xml - SAPUI5:是否可以在绑定过滤器中进行嵌套绑定
- sql - 我如何四舍五入到整个整数 postgres
- c++ - 变量模板的部分专业化
- c# - 实体框架 - 如何使用通用添加功能来比较导航属性
- wordpress - wordpress rest api taxonomy 仅返回 10
- python-3.x - 有人可以向我解释为什么 return 语句应该包含在这段代码中吗?
- javascript - 我如何从动态长度的javascript数组中创建n个块