2009-03-15 2 views
1

Im Console.ReadKey()を使用して、さまざまなオプションから選択できます。 この初期コードスニペットの前に、int型のカウンタ変数への出現をカウントするforループがあります。Console.ReadKeyをタイプ間で多くの変換をせずに値の選択に使用する良い方法はありますか?

ポイントは、Console.ReadKey()を使用してintを取得することです。次の方法

static int ReadKey() 
{ 
    ConsoleKeyInfo choice = Console.ReadKey(); 
    char convertedchoice = choice.KeyChar; 
    string convertedchoice2 = convertedchoice.ToString(); 
    int result = TryInt(convertedchoice2); 
    return result; 
} 

static int TryInt(string totry) 
{ 
    while (true) 
    { 
     int result; 
     if (int.TryParse(totry, out result)) 
     { 
      return result; 
     } 
     Console.WriteLine("Sorry, you need to enter a number. Try again."); 
    } 
} 

を使用することにより

int choice = ReadKey(); 
Console.WriteLine(""); 

if (choice < counter) 
{ 
    mail.to = result[counter-1].email; 
} 

は私がToStringメソッドを使用してみました()が、これは、それは私が最終的にそれをやらせるだろうと方法でした。 これは私にとっては無益なように見えるので、私は実際に何をすべきかという指針に感謝していますか?

編集:

私は以下のすべての良い答えの組み合わせで終わった。ありがとう、多くの人。

static int ReadKey() 
{ 
    while (true) 
    { 
     ConsoleKeyInfo choice = Console.ReadKey(); 
     if (char.IsDigit(choice.KeyChar)) 
     { 
      int answer = Convert.ToInt32(choice.KeyChar); 
      return answer - 48; //-48 because 0 is represented in unicode by 48 and 1 by 49 etc etc 
     } 
     Console.WriteLine("\nSorry, you need to input a number"); 
    } 
} 

答えて

4

選択肢が0..9のメニューシステムでは、これは問題ありません。しかし、大きな数字を読むためではありません。

あなたの全体のチェック・ロジックは、char.IsDigit()と非常に簡単に行うことができます。

if char.IsDigit(convertedchoice) 
{ 
    int result = convertedchoice - '0'; // char1 - char2 = int, in this case in 0..9 
    return result; 
} 
else ... 
+0

char.IsDigit()の使用は、私にとってはこの問題を浮き彫りにしていました。私からの質問に先制的な仕事をしてくれてありがとう! –

1

Convert.ToInt32(choice.KeyChar);に直接電話することができます。

これは少し単純化します。

+0

ちょうど私にエラーを与えること。 'char'に 'ToInt'の定義がなく、 'char'タイプの最初の引数を受け入れる拡張メソッド 'ToInt'がありませんでした。 –

+0

int result = Convert.ToInt32(choice.KeyChar);私は私の答えをより明示的に更新する予定です。 –

0

はあなたのコードを簡素化する方法はたくさんありますが、スタートのための変数にすべてを入れて回避しよう。一般的に、のようなもの:

(a + b + c)/2 

がのようなものよりも、より読みやすいです。これを考慮して

int A_plus_B = a + b 
int A_plus_B_plus_C = A_plus_B + c 
int answer = A_plus_B_plus_C/2 

、あなたが書くことができます:

static int ReadKey() 
{ 
    while (true) 
    { 
     char ch = Console.ReadKey().KeyChar; 
     int result; 
     if (int.TryParse(ch.toString(), out result)) 
     { 
      return result; 
     } 
    } 
} 
+0

アドバイスをいただきありがとうございますが、私の教授は実際に割り当てを入れてみるとわかりやすくするために、私たちのように書くことを実際に好んでいます。 –

+0

これは明確ではありません。そして、あなたが宿題を投稿するとき、あなたはそれをそのようにタグ付けすることになっています。 – MarkusQ

関連する問題