C#:shlwapi.dll 中 StrCmpLogicalW 的实现或替代
为了在我的应用程序中进行自然排序,我当前在 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;
}
}
因此,我正在寻找的是上述类的替代方案,它不使用 extern 函数。
For natural sorting in my application I currently P/Invoke a function called StrCmpLogicalW in shlwapi.dll. I was thinking about trying to run my application under Mono, but then of course I can't have this P/Invoke stuff (as far as I know anyways).
Is it possible to see the implementation of that method somewhere, or is there a good, clean and efficient C# snippet which does the same thing?
My code currently looks like this:
[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;
}
}
So, what I'm looking for is an alternative to the above class which doesn't use an extern function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我刚刚在 C# 中实现了自然字符串比较,也许有人会发现它很有用:
I just implemented natural string comparison in C#, perhaps someone might find it useful:
http://www.interact-sw.co.uk/iangblog/2007/ 12/13/natural-sorting 似乎就是您要寻找的。
(不,.NET 中没有内置与 StrCmpLogicalW 等效的托管组件)
http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting seems to be what you're looking for.
(and no, there is no managed equivalent to StrCmpLogicalW built into .NET)
我使用正则表达式来删除特殊字符。然后转换为 int。然后我比较了整数。
输入 :
Expected Output:
I used regular expression to remove special characters. then casting to int. then i compared integers.
input :
Expected Output:
如果您运行在 Windows XP 或更高版本上,您可以 PInvoke 到 shell 函数 StrCmpLogicalW:
然后是内部不安全类:
If you're running on Windows XP or newer, you can PInvoke to the shell function StrCmpLogicalW:
And then the internal unsafe class: