C#不会执行命令

时间:2015-06-22 18:28:47

标签: c#

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 ();
            }
        }
    }
}

我在该行上遇到的错误是“无法将类型为'System.ConsoleKeyInfo'的对象强制转换为'System.IConvertible'。”

1 个答案:

答案 0 :(得分:5)

使用Key属性:

char myChar = Convert.ToChar(Console.ReadKey().Key);

char c = Console.ReadKey().KeyChar;

修改

@juharr指出:

Console.ReadKey().Key始终返回大写字母,数字始终是数字值,即使按下shift也是如此。