首页 > 解决方案 > 如何使用 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));

如果为假不要反转它返回不带减如果为真加减。

标签: c#winforms

解决方案


您可以传入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); 

推荐阅读