在C#中将char转换为int [英] Convert char to int in C#
问题描述
我在c#中有一个字符:
I have a char in c#:
char foo = '2';
现在我想把2变成一个int。我发现Convert.ToInt32返回char的实际十进制值而不是数字2.以下将起作用:
Now I want to get the 2 into an int. I find that Convert.ToInt32 returns the actual decimal value of the char and not the number 2. The following will work:
int bar = Convert.ToInt32(new string(foo, 1));
int.parse仅适用于字符串。
int.parse only works on strings as well.
C#中没有本地函数从char转到int而不是字符串吗?我知道这是微不足道的,但似乎很奇怪,直接进行转换没有任何原生。
Is there no native function in C# to go from a char to int without making it a string? I know this is trivial but it just seems odd that there's nothing native to directly make the conversion.
推荐答案
有趣的答案,但文档换句话说:
Interesting answers but the docs say differently:
使用
GetNumericValue
方法来
转换Char
对象,表示数字值类型的
a数。使用
Parse
和TryParse
将字符串中的
字符转换为Char
对象。使用ToString
将Char
对象转换为String
object。
Use the
GetNumericValue
methods to convert aChar
object that represents a number to a numeric value type. UseParse
andTryParse
to convert a character in a string into aChar
object. UseToString
to convert aChar
object to aString
object.
http://msdn.microsoft.com/en-us/library/system.char.aspx
这篇关于在C#中将char转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!