您的位置:首页 > 编程语言 > C#

C#中关于实现IComparable接口的说明

2019-05-23 12:57 288 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_41399076/article/details/90478435

 最近在学习关于C# 语言 学习到了接口部分,发现了个有意思的现象,接口不能使用Sort方法对除int类型以外的数组数据类型排序

Sort方法应该是只能对int类型的数组排序 所以就要用到IComparable这个接口里面的CompareTo方法  通过实际的情况重写这个方法实现对非int类型的数组排序,在方法里面,返回值的不同表示了两个数组中两个元素比较的结果。

下面的代码就是解决了这个问题,通过引用IComparable 接口 重写内部的ToCompare方法,通过判断返回结果对数组中的元素进行排序。

[code]class Program
{
static void PrintOut(string s,Myclass[] mc) {
Console.Write(s);
foreach (var m in mc) {
Console.Write("{0} ",m.TheValue);
}Console.WriteLine("");
}
static void Main(string[] args)
{
var myInt = new[] { 20, 4, 16, 9, 2 };
Myclass[] mcArr = new Myclass[5];
for (int i = 0; i < 5; i++) {
mcArr[i] = new Myclass();
mcArr[i].TheValue = myInt[i];
}
PrintOut("Initial Order: ",mcArr);
Array.Sort(mcArr);
PrintOut("Sort Order: ",mcArr);
}
}
/*
* 创建类并实现引用
* 创建了一个实现接口的方法并且对方法进行重写,实现比较功能
*/
class Myclass : IComparable {
public int TheValue;
public int CompareTo(object obj) {
Myclass mc = (Myclass)obj;
if (this.TheValue < mc.TheValue) {
return -1;
}
if (this.TheValue > mc.TheValue) {
return 1;
}return 0;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: