从C#中的控制台读取整数时出错 [英] Error While reading integer from console in C#
本文介绍了从C#中的控制台读取整数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好专家,
首先,到目前为止所有帮助都是thx。现在我有一个小问题,但我需要一些建议。
Hello experts,
First of all, thx for all the help so far. Now i have a small issue but i need some suggestions.
int option; option = Convert.ToInt32(Console.ReadLine());
如果我输入一个0-9的数字,一切都很好,但是如果我输入一个错误的信件。有什么建议吗?
If i enter a number from 0-9 all works great, but if i enter a letter an error promts. Any suggestions pls?
推荐答案
而不是Convert.ToInt32,你应该使用Int32.TryParse。
Instead of Convert.ToInt32, you should use Int32.TryParse instead.
int option;
string inValue = Console.ReadLine();
if( Int32.TryParse(inValue, out option) )
{
// It converted successfully
}
else
{
// Apply some default value or prompt the user that an invalid value was entered.
}
代码工作正常。除非你知道输入是一个int,否则Convert.ToInt32是无用的。否则,获取值并使用int.TryParse。
The code is working fine. Convert.ToInt32 is useless unless you KNOW the input is an int. Otherwise, get the value and use int.TryParse.
我有一些辅助扩展函数,如:
I have some helper extension functions like:
public static class Extensions
{
/// <summary>Tries to parse a numeric value from this string.</summary>
/// <remarks>In case of error, takes the given defaultValue.</remarks>
/// <param name="defaultValue">Fallback in case of not matching input.</param>
/// <returns>the parsed value or, in case of parsing errors, the defaultValue</returns>
public static int ToInt(this string s, int defaultValue)
{
int value = int.TryParse(s, out value) ? value : defaultValue;
return value;
}
/// <summary>Tries to parse a numeric value from this string.</summary>
/// <remarks>In case of error, takes the given defaultValue.</remarks>
/// <param name="defaultValue">Fallback in case of not matching input.</param>
/// <returns>the parsed value or, in case of parsing errors, the defaultValue</returns>
public static double ToDouble(this string s, double defaultValue)
{
double value = double.TryParse(s, out value) ? value : defaultValue;
return value;
}
...
}
要像这样使用:
To be used like this:
int option = Console.ReadLine().ToInt(1234);
干杯
Andi
Cheers
Andi
这篇关于从C#中的控制台读取整数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文