You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 07:24:05