c# - 如何使用 bool 标志来决定是否在 MyComparer 类中使用 reverse ?
问题描述
private class MyComparer : IComparer<string>
{
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return -StrCmpLogicalW(psz1, psz2);
}
}
当我在返回行中添加减号时,它会将数组从最后一项排序到第一项。如果没有减号,它将对数组进行排序并保持从第一个到最后一个的顺序。
减号只是使排序也反转数组。
我想以某种方式制作一个布尔值,以便我可以选择是否反转数组。
用法 :
Array.Sort(files, new MyComparer());
我希望能够通过设置 true 或 false 来决定是否反转它,例如:
Array.Sort(filesRadar, new MyComparer(false));
如果为假不要反转它返回不带减如果为真加减。
解决方案
您可以传入reverse
构造函数:
private class MyComparer : IComparer<string>
{
// We may want to get rid of creation (see @aybe comment below)
public static readonly MyComparer Ascending = new MyComparer();
public static readonly MyComparer Descending = new MyComparer(false);
[DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public int Compare(string psz1, string psz2)
{
return (Reverse ? -1 : 1) * StrCmpLogicalW(psz1, psz2);
}
public MyComparer(bool reverse) {
Reverse = reverse;
}
public MyComparer()
: MyComparer(false) {}
public bool Reverse {get; private set;}
}
然后你可以把
Array.Sort(filesRadar, new MyComparer(false));
甚至
Array.Sort(filesRadar, MyComparer.Ascending);
推荐阅读
- r - 如何旋转完整的 facet_wrap ggplot?
- c++ - 当 p 是二维数组时,为什么 p、*p、&*p 具有相同的值?
- java - JFrames 消耗什么资源?
- arrays - 在 VBA for Excel 中循环数组函数时数据类型错误
- java - JdbcTemplate 在插入时返回 UUID “预期没有结果时返回了结果。”
- matlab - 我可以向量化从 MATLAB 中的元胞数组中提取数据吗?
- python - 使用 matplotlib 在 Jupyter 上更改绘图的背景颜色
- django - App 适用于 ModelChoiceField 但不适用于 ModelMultipleChoiceField
- c - STM32 人工智能
- python - 运行功能时未运行步骤定义方法