如何实现 VB6 中的 MIDB CHRB ASCB LENB RIGHTB LEFTB 函数?(200分)
以下是 VB6 的代码以及返回值,如何在 C# VS.NET 2005 中写函数实现下列各个函数的功能?
Function test()
Debug.Print AscB("c")
Debug.Print AscB("ccc")
Debug.Print AscB("中国")
Debug.Print LenB("c")
Debug.Print LenB("中国")
Debug.Print AscB(MidB("中", 1, 1))
Debug.Print AscB(MidB("中", 2, 1))
Debug.Print AscB(MidB("c", 1, 1))
Debug.Print AscB(MidB("c", 2, 1))
Debug.Print MidB("c", 2, 1) = ""
Debug.Print MidB("c", 1, 1) = "c"
' 上述代码的测试结果如下:
'99
'99
'45
'2
'4
'45
'78
'99
'0
'True
'False
'如何能实现他们的 C# .NET 2005 版本?
End Function
以下是我撰写的一些函数,能运行,但是结果都不对
public static char Chr(int CharCode)
{
//方法1
//return Convert.ToChar(CharCode);
//方法2
//byte[] bytes = new byte[1];
//bytes[0] = (byte)CharCode;
//return Encoding.GetEncoding("ASCII").GetString(bytes)[0];
//方法3
byte[] bytes = new byte[1];
bytes[0] = (byte)CharCode;
return Encoding.Default.GetString(bytes)[0];
}
public static int Asc(string CharWord)
{
//方法1
//return (int)Encoding.ASCII.GetBytes(CharWord)[0];
//方法2
//return (int)Encoding.GetEncoding("ASCII").GetBytes(CharWord)[0];
//方法3
return (int)Encoding.Default.GetBytes(CharWord)[0];
}
public static int LenB(string CharWords)
{
//LenB("c")=1
//return Encoding.Default.GetBytes(CharWords).Length;
//vb6 中 LenB("c") 是2,所以这里也要改为 Unicode
//return Encoding.Unicode.GetBytes(CharWords).Length;
// 第三种方法
return (int)Encoding.Unicode.GetByteCount(CharWords);
}
public static int AscB(string CharWord)
{
//int bytes = Encoding.Unicode.GetByteCount(CharWord); //调试时使用
if (CharWord == "")
{
return 0;
}
else
{
return (int)Encoding.Unicode.GetBytes(CharWord)[0];
}
}
public static string ChrB(int CharCode)
{
byte[] bytes = new byte[1];
bytes[0] = (byte)CharCode;
return Encoding.Default.GetString(bytes)[0].ToString();
}
#region MidB
public static string MidB(string CharWords, int Start)
{
return MidB(CharWords, Start, 0);
}
public static string MidB(string CharWords, int Start, int ByteSize)
{
//byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(CharWords);
byte[] bytes = Encoding.Unicode.GetBytes(CharWords);
Debug.Print(CharWords + "的字节数为:" + bytes.GetLength(0).ToString());
if (ByteSize == 0)
{
return Encoding.Unicode.GetString(bytes, Start - 1, bytes.Length - Start + 1);
}
else
{
return Encoding.Unicode.GetString(bytes, Start - 1, ByteSize);
}
}
#endregion