Jon*_*eet 137
你的意思是"A"(a string
)还是"A"(a char
)?
int unicode = 65;
char character = (char) unicode;
string text = character.ToString();
Run Code Online (Sandbox Code Playgroud)
请注意,我已经将Unicode而不是ASCII称为C#的本机字符编码; 基本上每个char
都是UTF-16代码点.
小智 10
这适用于我的代码.
string asciichar = (Convert.ToChar(65)).ToString();
Run Code Online (Sandbox Code Playgroud)
返回: asciichar = 'A';
有几种方法可以做到这一点。
使用char struct(以字符串形式再次返回)
string _stringOfA = char.ConvertFromUtf32(65);
int _asciiOfA = char.ConvertToUtf32("A", 0);
Run Code Online (Sandbox Code Playgroud)
简单地转换值(显示的字符和字符串)
char _charA = (char)65;
string _stringA = ((char)65).ToString();
Run Code Online (Sandbox Code Playgroud)
使用ASCIIEncoding。
可以在循环中使用它来完成整个字节数组
var _bytearray = new byte[] { 65 };
ASCIIEncoding _asiiencode = new ASCIIEncoding();
string _alpha = _asiiencode .GetString(_newByte, 0, 1);
Run Code Online (Sandbox Code Playgroud)
您可以重写类型转换器类,这将使您可以对值进行一些精美的验证:
var _converter = new ASCIIConverter();
string _stringA = (string)_converter.ConvertFrom(65);
int _intOfA = (int)_converter.ConvertTo("A", typeof(int));
Run Code Online (Sandbox Code Playgroud)
这是课程:
public class ASCIIConverter : TypeConverter
{
// Overrides the CanConvertFrom method of TypeConverter.
// The ITypeDescriptorContext interface provides the context for the
// conversion. Typically, this interface is used at design time to
// provide information about the design-time container.
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(int))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
// Overrides the ConvertFrom method of TypeConverter.
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is int)
{
//you can validate a range of int values here
//for instance
//if (value >= 48 && value <= 57)
//throw error
//end if
return char.ConvertFromUtf32(65);
}
return base.ConvertFrom(context, culture, value);
}
// Overrides the ConvertTo method of TypeConverter.
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(int))
{
return char.ConvertToUtf32((string)value, 0);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
Run Code Online (Sandbox Code Playgroud)