C# 有没有一种好方法可以使用Console.ReadKey在值之间进行选择,而不用在类型之间进行大量转换?

C# 有没有一种好方法可以使用Console.ReadKey在值之间进行选择,而不用在类型之间进行大量转换?,c#,types,console,C#,Types,Console,我正在使用Console.ReadKey()从许多选项中进行选择,这些选项随时间而变化。 在这个初始代码段之前,有一个for循环,它将发生的事件计数到int类型的计数器变量中 要点是使用Console.ReadKey()获取int int choice = ReadKey(); Console.WriteLine(""); if (choice < counter) { mail.to = result[counter-1].email; } 我试着使用ToString(),但

我正在使用Console.ReadKey()从许多选项中进行选择,这些选项随时间而变化。 在这个初始代码段之前,有一个for循环,它将发生的事件计数到int类型的计数器变量中

要点是使用Console.ReadKey()获取int

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

您只需调用
Convert.ToInt32(choice.KeyChar)直接


这会简化一点。

您只需调用
Convert.ToInt32(choice.KeyChar)直接


这将使它简化一点。

对于选择0..9的菜单系统,这是合理的。但不适合阅读更大的数字

使用char.IsDigit()可以简化整个检查逻辑:


对于选项为0..9的菜单系统,这是合理的。但不适合阅读更大的数字

使用char.IsDigit()可以简化整个检查逻辑:


有很多方法可以简化代码,但首先要避免将所有内容都放入变量中。一般来说,以下情况:

(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
比以下内容更容易阅读:

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

有很多方法可以简化代码,但首先要避免将所有内容都放入变量中。一般来说,以下情况:

(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
比以下内容更容易阅读:

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

这就给了我一个错误。”char'不包含'ToInt'的定义,并且找不到接受类型为'char'的第一个参数的扩展方法'ToInt'。它应该是int result=Convert.ToInt32(choice.KeyChar);我会更新我的答案,使之更加明确。这只会给我带来错误。”char'不包含'ToInt'的定义,并且找不到接受类型为'char'的第一个参数的扩展方法'ToInt'。它应该是int result=Convert.ToInt32(choice.KeyChar);我会更新我的答案,使之更加明确。谢谢你的建议,但我的教授实际上更喜欢我们在交作业时这样写,以便清楚。这不是清楚。仅供参考,当你发布作业时,你应该给它贴上这样的标签。谢谢你的建议,但我的教授实际上更喜欢我们在交作业时这样写,这样才能清楚。这不是清楚。仅供参考,当你发布作业时,你应该给它贴上这样的标签。char.IsDigit()的使用让我大开眼界,解决了这个问题。谢谢你对我提出的问题先发制人!在发现这个问题时,char.IsDigit()的使用让我大开眼界。谢谢你对我提出的问题先发制人!