Convert char to int in C#(在 C# 中将 char 转换为 int)
问题描述
我在 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 对象,它表示数字到数值类型.利用Parse 和 TryParse 转换一个将字符串中的字符转换为 Char目的.使用 ToString 转换 Char对象到 String 对象.
Use the
GetNumericValuemethods to convert aCharobject that represents a number to a numeric value type. UseParseandTryParseto convert a character in a string into aCharobject. UseToStringto convert aCharobject to aStringobject.
http://msdn.microsoft.com/en-us/库/system.char.aspx
这篇关于在 C# 中将 char 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将 char 转换为 int
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
