How to cast int digit to char without loosing digit value in c#(如何将 int 数字转换为 char 而不会在 c# 中丢失数字值)
问题描述
Mabby 这是一个愚蠢的问题,但我怎样才能将 int 类型的数字转换为 char 类型的数字?
Mabby it's a stupid question, but how can I cast digit of type int to digit of type char?
标准转换 OP 不这样做:
Standard conversion OPs doesn't do this:
int x = 5;
char myChar = Convert.ToChar(5); // myChar is now a unicode character
char secondChar = (char)x; // again I get a unicode character, not a digit '5'
我需要这个,因为我有一个返回 Char 的 IEnumerable 的方法,并且我需要以某种方式返回 ints 的集合.
I need this because I have a method that returns IEnumerable of Char and I need to return a collection of ints somehow.
例如:
int[] {1, 2, 3}
转换成
char[] {'1', '2', '3'}
在 C# 中可以做这样的转换吗?
Is it possible to do such a conversion in C#?
推荐答案
在转换为 char 之前将 48 添加到您的 int 值中:
Add 48 to your int value before converting to char:
char c = (char)(i + 48);
或者为int[] -> char[] 转换:
Or for int[] -> char[] conversion:
var source = new int[] { 1, 2, 3 };
var results = source.Select(i => (char)(i + 48)).ToArray();
它有效,因为 ASCII 表中的 '0' 字符有 48 值.但只有当您的 int 值介于 0 和 9 之间时,它才会起作用.
It works, because '0' character in ASCII table has 48 value. But it will work only if your int values is between 0 and 9.
这篇关于如何将 int 数字转换为 char 而不会在 c# 中丢失数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 int 数字转换为 char 而不会在 c# 中丢失数字值
基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
