Array.Sort的执行步骤

iamxia iamxia 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
主要问题是
1、既然Array.Sort本身具体有排序作用为什么还要参数 myComparer?难道仅仅是为了倒序?
2、myReverserClass::Compare(object x, object y)中的X,Y哪里来的?程序中并没有显式的调用compare函数




// 程序如下
using System;
using System.Collections;

public class SamplesArray
{
public class myReverserClass : IComparer
{
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y )
{
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}

}

public static void Main()
{

// Creates and initializes a new Array and a new custom comparer.
String[] myArr = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", "the", "lazy", "dog" };
IComparer myComparer = new myReverserClass();

// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintIndexAndValues( myArr );

// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myArr, 1, 3, myComparer ); //【×××】
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintIndexAndValues( myArr );

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myArr, myComparer ); //【×××】
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintIndexAndValues( myArr );

}

public static void PrintIndexAndValues( String[] myArr )
{
for ( int i = 0; i < myArr.Length; i++ )
{
Console.WriteLine( " [{0}] : {1}", i, myArr[i] );
}
Console.WriteLine();
}
}


/*
This code produces the following output.

The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog



After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog



After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/

...全文
评论 7
收藏 已收藏
分享
返回顶部
iamxia
C# 111,128 成员 642,536 内容