[英]C# won't execute a command
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
string nume;
int A = 0;
int B = 0;
int C = 0;
char comanda;
Console.WriteLine ("Va rugam sa va introduceti numele:");
nume = Convert.ToString (Console.ReadLine());
Console.WriteLine ("\n Buna ziua, " + nume + ", ce doriti sa comandati?");
Console.WriteLine ("\n Castraveti(A)");
Console.WriteLine ("\n Ceai(B)");
Console.WriteLine ("\n Gogosi!(C)");
comanda = Convert.ToChar (Console.ReadKey()); // Here is the problem, when I enter A, B or C the console will just shut down.
if(comanda == A) {
int raspuns;
int D = 0;
int E = 0;
Console.WriteLine ("Murati(D) sau proaspeti(E)?");
raspuns = Convert.ToInt32 (Console.ReadLine());
if (raspuns == D) {
Console.WriteLine ("Poftiti castravetii murati");
}
if (raspuns == E){
Console.WriteLine ("Poftiti castravetii proaspeti");
}
} else if(comanda == B){
Console.WriteLine ("Multumim pentru comanda, aici este ceaiul");
} else if(comanda == C) {
int X = 0;
int Y = 0;
int raspuns;
Console.WriteLine ("Aa! Buna alegere, nu crezi?\n Da(X), nu(Y)");
raspuns = Convert.ToInt32 (Console.ReadLine());
if (raspuns == X){
Console.WriteLine ("Si eu!! Poti lua gogoasa, nici nu mai trebuie sa platesti :D");
}
if (raspuns == Y){
Console.WriteLine (".....mda, nu te inteleg. Nu o sa mai primesti gogoasa!");
}
Console.ReadKey ();
}
}
}
}
The error I get on that line is "Unable to cast object of type 'System.ConsoleKeyInfo' to type 'System.IConvertible'." 我在该行上遇到的错误是“无法将类型为'System.ConsoleKeyInfo'的对象强制转换为类型为'System.IConvertible'。”
Use the Key
Property: 使用
Key
属性:
char myChar = Convert.ToChar(Console.ReadKey().Key);
or 要么
char c = Console.ReadKey().KeyChar;
Edit: 编辑:
As @juharr pointed out: 正如@juharr指出的那样:
Console.ReadKey().Key
always returns the upper case letter and for numbers always the numeric value, even if shift is pressed. Console.ReadKey().Key
始终返回大写字母,而数字始终返回数值,即使按下shift键也是如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.