引用VB运行时不是一个好主意

Aug 14, 2009 at 3:48 AM

你引用了VB运行时来做简繁体转换,其实有更简单的做法,VB运行时也是这样做的

using System.Runtime.InteropServices;


        internal enum TextCnversionTypes
        {
            None = 0,
            Traditional = 1,
            Simplified = 2,
            Wide = 4,
            Narrow = 8,
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        private static extern int LCMapString(int Locale, uint dwMapFlags, [MarshalAs(UnmanagedType.LPTStr)] string lpSrcStr, int cchSrc, IntPtr lpDestStr, int cchDest);
        private const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
        private const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;
        private const int LCMAP_NARROW_CHINESE = 0x0400000;
        private const int LCMAP_WIDE_CHINESE = 0x0800000;

        internal static String ConvertString(String Content, TextCnversionTypes ConversionType)
        {
            switch (ConversionType)
            {
                default:
                    uint dwMapFlags = 0;
                    if ((ConversionType & TextCnversionTypes.Simplified) != TextCnversionTypes.None)
                        dwMapFlags |= LCMAP_SIMPLIFIED_CHINESE;
                    else if ((ConversionType & TextCnversionTypes.Traditional) != TextCnversionTypes.None)
                        dwMapFlags |= LCMAP_TRADITIONAL_CHINESE;

                    if ((ConversionType & TextCnversionTypes.Narrow) != TextCnversionTypes.None)
                        dwMapFlags |= LCMAP_NARROW_CHINESE;
                    else if ((ConversionType & TextCnversionTypes.Wide) != TextCnversionTypes.None)
                        dwMapFlags |= LCMAP_WIDE_CHINESE;

                    int cb = (Content.Length * 2) + 2;
                    IntPtr lpDestStr = Marshal.AllocHGlobal(cb);
                    LCMapString(0x804, dwMapFlags, Content, -1, lpDestStr, cb);
                    string str = Marshal.PtrToStringUni(lpDestStr);
                    Marshal.FreeHGlobal(lpDestStr);
                    return str;
            }
        }

 

Coordinator
Aug 14, 2009 at 4:41 AM

引用VB运行时的坏处是什么,能详细说说吗?

如果直接调用windows API ,我不知道兼容性会怎么样,特别是64位系统下会怎么样,没有测试过。

 

Aug 14, 2009 at 4:55 AM

坏处是你需要多加载一个程序集:)

32位兼容性没问题,上面的代码就是反编译vb运行时的,64位没测试过

Aug 14, 2009 at 5:04 AM

64位系统测试过了,无论程序是x86还是x64,都能正确跑

Coordinator
Aug 14, 2009 at 5:08 AM

多加载一个程序集似乎还不是不能忍受。启动时间增加的开销和加载字典比起来应该要小很多。我觉得兼容性更重要一些,能不调用API 尽量不调用API,毕竟我没有微软的测试工程师那种条件,可以测试所有系统的兼容性。

 

Aug 14, 2009 at 5:42 AM

你也有理,不同场合有不同的需求。你的文章和项目都不错,希望你继续改进。