C# 从int变量获取ASCII

C# 从int变量获取ASCII,c#,.net,C#,.net,这是我试过的 int two = 2; int asciiX = (int) 'x'; int asciiTwo = (int) two; Console.WriteLine("The ascii value of 2 is " + asciiTwo); Console.WriteLine("The ascii value of x is " + asciiX);); 我希望

这是我试过的

            int two = 2;
            int asciiX = (int) 'x';
            int asciiTwo = (int) two;
            Console.WriteLine("The ascii value of 2 is " + asciiTwo);
            Console.WriteLine("The ascii value of x is " + asciiX););
我希望输出为50,因为2的ascii值为50(即“2”的ascii码)

但我得到了这个结果:

The ascii value of 2 is 2
The ascii value of x is 120 (it's working for x)

我知道如果我把
intasciitwo='2'它可以工作,但它不是直接从变量中处理我该怎么做,才能得到整数变量中的数字的ascii码

two
是一个值为
2
int
。您正在将
int
转换为
int
。这不会改变任何事情

至少可以使用两种方法获取ASCII值:

(int)(two.ToString())[0] //the first char of the string representation of two
(int)(two + '0') //numbers start at '0' in the ASCII table

two
是一个值为
2
int
。您正在将
int
转换为
int
。这不会改变任何事情

至少可以使用两种方法获取ASCII值:

(int)(two.ToString())[0] //the first char of the string representation of two
(int)(two + '0') //numbers start at '0' in the ASCII table

two
变量声明为
int
int
int
就是
int
本身

您需要将其声明为
char
string

char two = '2';
int asciiTwo = (int) two;

two
变量声明为
int
int
int
就是
int
本身

您需要将其声明为
char
string

char two = '2';
int asciiTwo = (int) two;