如何在MyComparer类中通过bool参数控制排序是否反转?
实现代码
private class MyComparer : IComparer<string> { [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)] private static extern int StrCmpLogicalW(string psz1, string psz2); // 存储排序反转配置的私有字段 private readonly bool _isReverse; // 新增带bool参数的构造函数 public MyComparer(bool isReverse) { _isReverse = isReverse; } public int Compare(string psz1, string psz2) { int originalCompareResult = StrCmpLogicalW(psz1, psz2); // 根据构造参数决定是否对结果取反 return _isReverse ? -originalCompareResult : originalCompareResult; } }
使用说明
- 传入
false使用原生逻辑正序排序:
Array.Sort(filesRadar, new MyComparer(false));
- 传入
true对结果取反实现倒序排序:
Array.Sort(filesRadar, new MyComparer(true));
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

