我正在努力将大型VB6代码库移植到.NET。它是一个以数据库为中心的软件,数据库本身保存VB6格式字符串,后来加载并用于显示数据库中的其他数据。
我的问题,如this article,是如何移植它的。但是,为该问题选择的答案不足以满足我的需求。我依赖专门设计的库来向后兼容我专门雇用的语言,我感到很不舒服。
答案 0 :(得分:15)
VB6使用的格式化例程实际上内置在操作系统中。 Oleaut32.dll,VarFormat()函数。考虑到有多少代码依赖它,它已经存在了15年并将永远存在。尝试将格式化字符串转换为.NET复合格式化字符串是一项毫无希望的任务。只需使用操作系统功能。
以下是使用链接线程中的示例执行此操作的示例程序:
using System;
using System.Runtime.InteropServices;
class Program {
static void Main(string[] args) {
Console.WriteLine(Vb6Format("hi there", ">"));
Console.WriteLine(Vb6Format("hI tHeRe", "<"));
Console.WriteLine(Vb6Format("hi there", ">!@@@... not @@@@@"));
Console.ReadLine();
}
public static string Vb6Format(object expr, string format) {
string result;
int hr = VarFormat(ref expr, format, 0, 0, 0, out result);
if (hr != 0) throw new COMException("Format error", hr);
return result;
}
[DllImport("oleaut32.dll", CharSet = CharSet.Unicode)]
private static extern int VarFormat(ref object expr, string format, int firstDay, int firstWeek, int flags,
[MarshalAs(UnmanagedType.BStr)] out string result);
}
答案 1 :(得分:0)
您最好的选择可能是自己编写转换库,但这可能不是您希望得到的答案。
答案 2 :(得分:0)
以下是一些F#代码,它们将大多数预定义和自定义VB6样式的数字和日期格式字符串转换为适合String.Format
的字符串。当然,它很容易从C#或VB调用。
open System
module VB6Format =
/// Converts a VB6-style format string to something suitable for String.Format()
let Convert(vb6Format) =
if String.IsNullOrWhiteSpace(vb6Format) then "{0}" else
match if vb6Format.Length > 1 then vb6Format.ToUpperInvariant() else vb6Format with
// PREDEFINED NUMERIC: http://msdn.microsoft.com/en-us/library/y006s0cz(v=vs.71).aspx
| "GENERAL NUMBER" | "G" -> "{0:G}"
| "g" -> "{0:g}"
| "CURRENCY" | "C" | "c" -> "{0:C}"
| "FIXED" | "F" -> "{0:F}"
| "f" -> "{0:f}"
| "STANDARD" | "N" | "n" -> "{0:N}"
| "PERCENT" | "P" | "p" -> "{0:P}"
| "SCIENTIFIC" -> "{0:E2}"
| "E" | "e" -> "{0:E6}"
| "D" | "d" -> "{0:D}"
| "X" | "x" -> "{0:X}"
| "YES/NO" | "ON/OFF" // we can't support these
| "TRUE/FALSE" -> "{0}"
// PREDEFINED DATE/TIME: http://msdn.microsoft.com/en-us/library/362btx8f(v=VS.71).aspx
| "GENERAL DATE" | "G" -> "{0:G}"
| "LONG DATE" | "D" -> "{0:D}"
| "MEDIUM DATE"
| "SHORT DATE" | "d" -> "{0:d}"
| "LONG TIME" | "T" -> "{0:T}"
| "MEDIUM TIME"
| "SHORT TIME" | "t" -> "{0:t}"
| "M" | "m" -> "{0:M}"
| "R" | "r" -> "{0:R}"
| "s" -> "{0:s}"
| "u" -> "{0:u}"
| "U" -> "{0:U}"
| "Y" | "y" -> "{0:Y}"
// USER-DEFINED: http://msdn.microsoft.com/en-us/library/4fb56f4y(v=vs.71).aspx
// http://msdn.microsoft.com/en-us/library/73ctwf33(v=VS.71).aspx
// The user-defined format strings translate more-or-less exactly, so we're just going to use them.
| _ -> sprintf "{0:%s}" vb6Format