简体   繁体   English

将 int 转换为 Char c#?

[英]Converting an int to a Char c#?

I want to be able to Read a value from the operator M/F for male or female and return seperate blocks of text for each respective entry.我希望能够从运算符 M/F 读取男性或女性的值,并为每个条目返回单独的文本块。

Char gender;
int TempValue;
Console.WriteLine("Please enter your name");
Console.CursorVisible=true;
String name = Console.ReadLine();
Console.WriteLine(" Greetings, faire travler {0} you are about to depart on a rather exciting adventure, but first are you male or female?", name);
Console.WriteLine("(M/F)");

TempValue = Console.Read();
Console.WriteLine("{0}", TempValue);
gender = Char.Parse(TempValue);

Now i get an error saying I "cannot convert from 'INT' to 'string' which I really dont understand. Becuase im trying to parse it into a char not a string.现在我收到一个错误,说我“无法从 'INT' 转换为 'string',我真的不明白。因为我试图将它解析为字符而不是字符串。

Char.Parse takes a string as it's parameter, but TempValue is declared as an int . Char.Parse接受一个string作为它的参数,但TempValue被声明为一个int You can either ToString TempValue :您可以使用ToString TempValue

gender = Char.Parse(TempValue.ToString());

or use Convert.ToChar() , which takes an object :或使用Convert.ToChar() ,它接受一个object

gender = Convert.ToChar(TempValue);

Console.Read() returns the ascii value of the character you entered. Console.Read()返回您输入的字符的 ascii 值。 (In case of 'M' it's 77) char.Parse(TempValue) expects TempValue to be a string and that it contains exactly one character. (在 'M' 的情况下,它是 77) char.Parse(TempValue)期望TempValue是一个string ,并且它只包含一个字符。 So, this is what you would use to convert the string "M" to the character 'M'.因此,这就是您将字符串“M”转换为字符“M”的方法。 But you don't have the string "M";但是你没有字符串“M”; you have the int 77.你有 int 77。
In this case, you can simply cast it:在这种情况下,您可以简单地投射它:

char gender = (char)TempValue;

Alternatively, you can use Console.ReadLine() , which returns a string and then take the first character:或者,您可以使用Console.ReadLine() ,它返回一个string ,然后取第一个字符:

string input = Console.ReadLine();
char gender = input[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM