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