C#char to int [英] C# char to int

查看:164
本文介绍了C#char to int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在c#中有一个char:

  char foo ='2' 



现在我想把2变成一个int。我发现Convert.ToInt32返回char的实际十进制值,而不是数字2.以下将工作:

  int bar = Convert.ToInt32(new string(foo,1)); 

int.parse仅适用于字符串。



在C#中没有本地函数从char到int而不是字符串?我知道这是微不足道的,但它似乎很奇怪,没有原生的直接进行转换。

解决方案

有趣的答案,换句话说:


使用GetNumericValue方法
将表示
a数字的Char对象转换为数值类型。使用
Parse和TryParse将字符串中的
字符转换为Char
对象。使用ToString将Char
对象转换为String对象。


http://msdn.microsoft.com/en-us/library/system.char.aspx p>

So I have a char in c#:

char foo = '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 only works on strings as well.

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:

Use the GetNumericValue methods to convert a Char object that represents a number to a numeric value type. Use Parse and TryParse to convert a character in a string into a Char object. Use ToString to convert a Char object to a String object.

http://msdn.microsoft.com/en-us/library/system.char.aspx

这篇关于C#char to int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆