C#:在 shlwapi.dll 中实现或替代 StrCmpLogicalW

标签 c# extern natural-sort

为了在我的应用程序中进行自然排序,我目前在 shlwapi.dll 中 P/Invoke 了一个名为 StrCmpLogicalW 的函数。我正在考虑尝试在 Mono 下运行我的应用程序,但是当然我不能拥有这个 P/Invoke 东西(据我所知)。

是否有可能在某处看到该方法的实现,或者是否有一个好的、干净且高效的 C# 片段可以做同样的事情?

我的代码目前看起来像这样:

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public class NaturalStringComparer : IComparer<string>
{
    private readonly int modifier = 1;

    public NaturalStringComparer() : this(false) {}
    public NaturalStringComparer(bool descending)
    {
        if (descending) modifier = -1;
    }

    public int Compare(string a, string b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a ?? "", b ?? "") * modifier;
    }
}

所以,我正在寻找的是不使用外部函数的上述类的替代方案。

最佳答案

我刚刚在 C# 中实现了自然字符串比较,也许有人会发现它有用:

public class NaturalComparer : IComparer<string>
{
   public int Compare(string x, string y)
   {
      if (x == null && y == null) return 0;
      if (x == null) return -1;
      if (y == null) return 1;

      int lx = x.Length, ly = y.Length;

      for (int mx = 0, my = 0; mx < lx && my < ly; mx++, my++)
      {
         if (char.IsDigit(x[mx]) && char.IsDigit(y[my]))
         {
            long vx = 0, vy = 0;

            for (; mx < lx && char.IsDigit(x[mx]); mx++)
               vx = vx * 10 + x[mx] - '0';

            for (; my < ly && char.IsDigit(y[my]); my++)
               vy = vy * 10 + y[my] - '0';

            if (vx != vy)
               return vx > vy ? 1 : -1;
         }

         if (mx < lx && my < ly && x[mx] != y[my])
            return x[mx] > y[my] ? 1 : -1;
      }

      return lx - ly;
   }
}

关于C#:在 shlwapi.dll 中实现或替代 StrCmpLogicalW,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8793856/

相关文章:

c# - c# 中的字符串相等运算符 ==

c++ - extern "C"变量名 "virtual"

scala - Scala 中有序特征的问题

iOS:自然排序

sql - MySQL中的自然排序

C# 泛型多态

c# - OpenXml:以编程方式获取脚注的 NumberingRestart 设置

c# - 如何使用 Parallel.ForEach 正确写入文件?

c - 为什么使用 File1 中定义的数组在 File2 中工作(仅在那里声明),即使没有 "extern"?

c++ - extern 必须有权访问类构造函数吗?