VB 有几个本机函数用于将 char 转换为 ASCII 值,反之亦然 - Asc() 和 Chr()。
现在我需要在 C# 中获得等效的功能。最好的方法是什么?
您始终可以添加对 Microsoft.VisualBasic 的引用,然后使用完全相同的方法:Strings.Chr和Strings.Asc。
这是获得完全相同功能的最简单方法。
因为Asc()
您可以将其char
转换为int
这样的:
int i = (int)your_char;
并且Chr()
你可以char
从一个int
这样的转换回:
char c = (char)your_int;
这是一个演示整个事情的小程序:
using System;
class Program
{
static void Main()
{
char c = 'A';
int i = 65;
// both print "True"
Console.WriteLine(i == (int)c);
Console.WriteLine(c == (char)i);
}
}
我使用 resharper 得到了这些,确切的代码由 VB 在你的机器上运行
/// <summary>
/// Returns the character associated with the specified character code.
/// </summary>
///
/// <returns>
/// Returns the character associated with the specified character code.
/// </returns>
/// <param name="CharCode">Required. An Integer expression representing the <paramref name="code point"/>, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> < 0 or > 255 for Chr.</exception><filterpriority>1</filterpriority>
public static char Chr(int CharCode)
{
if (CharCode < (int) short.MinValue || CharCode > (int) ushort.MaxValue)
throw new ArgumentException(Utils.GetResourceString("Argument_RangeTwoBytes1", new string[1]
{
"CharCode"
}));
if (CharCode >= 0 && CharCode <= (int) sbyte.MaxValue)
return Convert.ToChar(CharCode);
try
{
Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage());
if (encoding.IsSingleByte && (CharCode < 0 || CharCode > (int) byte.MaxValue))
throw ExceptionUtils.VbMakeException(5);
char[] chars = new char[2];
byte[] bytes = new byte[2];
Decoder decoder = encoding.GetDecoder();
if (CharCode >= 0 && CharCode <= (int) byte.MaxValue)
{
bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 1, chars, 0);
}
else
{
bytes[0] = checked ((byte) ((CharCode & 65280) >> 8));
bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 2, chars, 0);
}
return chars[0];
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(char String)
{
int num1 = Convert.ToInt32(String);
if (num1 < 128)
return num1;
try
{
Encoding fileIoEncoding = Utils.GetFileIOEncoding();
char[] chars = new char[1]
{
String
};
if (fileIoEncoding.IsSingleByte)
{
byte[] bytes = new byte[1];
fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
return (int) bytes[0];
}
byte[] bytes1 = new byte[2];
if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
return (int) bytes1[0];
if (BitConverter.IsLittleEndian)
{
byte num2 = bytes1[0];
bytes1[0] = bytes1[1];
bytes1[1] = num2;
}
return (int) BitConverter.ToInt16(bytes1, 0);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(string String)
{
if (String == null || String.Length == 0)
throw new ArgumentException(Utils.GetResourceString("Argument_LengthGTZero1", new string[1]
{
"String"
}));
return Strings.Asc(String[0]);
}
资源只是存储错误消息,因此您希望以某种方式忽略它们,而您无权访问的其他两种方法如下:
internal static Encoding GetFileIOEncoding()
{
return Encoding.Default;
}
internal static int GetLocaleCodePage()
{
return Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage;
}
Strings.Asc 不等同于可以超出 127 代码值的非 ASCII 字符的普通 C# 转换。我在 https://social.msdn.microsoft.com/Forums/vstudio/en-US/13fec271-9a97-4b71-ab28-4911ff3ecca0/equivalent-in-c-of-asc-chr-functions-of上找到的答案-vb?forum=csharpgeneral 相当于这样的东西:
static int Asc(char c)
{
int converted = c;
if (converted >= 0x80)
{
byte[] buffer = new byte[2];
// if the resulting conversion is 1 byte in length, just use the value
if (System.Text.Encoding.Default.GetBytes(new char[] { c }, 0, 1, buffer, 0) == 1)
{
converted = buffer[0];
}
else
{
// byte swap bytes 1 and 2;
converted = buffer[0] << 16 | buffer[1];
}
}
return converted;
}
或者,如果您想要读取交易,请添加对 Microsoft.VisualBasic 程序集的引用。
对于 Chr(),您可以使用:
char chr = (char)you_char_value;
在 C# 中,您可以使用 Char.ConvertFromUtf32 语句
int intValue = 65; \\ Letter A
string strVal = Char.ConvertFromUtf32(intValue);
相当于VB的
Dim intValue as integer = 65
Dim strValue As String = Char.ConvertFromUtf32(intValue)
无需 Microsoft.VisualBasic 参考
将此方法添加到 C# 中
private int Asc(char String)
{
int int32 = Convert.ToInt32(String);
if (int32 < 128)
return int32;
try
{
Encoding fileIoEncoding = Encoding.Default;
char[] chars = new char[1] { String };
if (fileIoEncoding.IsSingleByte)
{
byte[] bytes = new byte[1];
fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
return (int)bytes[0];
}
byte[] bytes1 = new byte[2];
if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
return (int)bytes1[0];
if (BitConverter.IsLittleEndian)
{
byte num = bytes1[0];
bytes1[0] = bytes1[1];
bytes1[1] = num;
}
return (int)BitConverter.ToInt16(bytes1, 0);
}
catch (Exception ex)
{
throw ex;
}
}
`
我从 Microsoft.VisualBasic.dll 中提取了 Asc() 函数:
public static int Asc(char String)
{
int num;
byte[] numArray;
int num1 = Convert.ToInt32(String);
if (num1 >= 128)
{
try
{
Encoding fileIOEncoding = Encoding.Default;
char[] str = new char[] { String };
if (!fileIOEncoding.IsSingleByte)
{
numArray = new byte[2];
if (fileIOEncoding.GetBytes(str, 0, 1, numArray, 0) != 1)
{
if (BitConverter.IsLittleEndian)
{
byte num2 = numArray[0];
numArray[0] = numArray[1];
numArray[1] = num2;
}
num = BitConverter.ToInt16(numArray, 0);
}
else
{
num = numArray[0];
}
}
else
{
numArray = new byte[1];
fileIOEncoding.GetBytes(str, 0, 1, numArray, 0);
num = numArray[0];
}
}
catch (Exception exception)
{
throw exception;
}
}
else
{
num = num1;
}
return num;
}
以下例程适用于 .net 标准 2.0 + .net 5 的 COM 互操作服务器环境和经典 ASP/VB6 客户端,代码页为 1252。
我没有用其他代码页测试它:
public static int Asc(char String)
{
int int32 = Convert.ToInt32(String);
if (int32 < 128)
return int32;
Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
char[] chars = new char[1] { String };
if (encoding.IsSingleByte)
{
byte[] bytes = new byte[1];
encoding.GetBytes(chars, 0, 1, bytes, 0);
return (int)bytes[0];
}
byte[] bytes1 = new byte[2];
if (encoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
return (int)bytes1[0];
if (BitConverter.IsLittleEndian)
{
byte num = bytes1[0];
bytes1[0] = bytes1[1];
bytes1[1] = num;
}
return (int)BitConverter.ToInt16(bytes1, 0);
}
//Char to Int - ASC("]")
int lIntAsc = (int)Char.Parse("]");
Console.WriteLine(lIntAsc); //Return 91
//Int to Char
char lChrChar = (char)91;
Console.WriteLine(lChrChar ); //Return "]"
给定 char c 和 int i,以及函数 fi(int) 和 fc(char):
从 char 到 int(类似于 VB Asc()):将 char 显式转换为 int:int i = (int)c;
或隐式转换(提升):fi(char c) {i+= c;}
从 int 到 char(类似于 VB Chr()):
将 int 显式转换为 char:char c = (char)i, fc(int i) {(char)i};
不允许隐式转换,因为 int 比 char 更宽(具有更大的值范围)