缺乏IsNumeric函数的C# [英] Lack of IsNumeric function in C#
问题描述
有一件事情已经困扰我关于C#,因为它的发行是缺乏一个通用IsNumeric函数的。我知道这是很难产生的一站式解决方案,借以了解物质,如果值是数字。
One thing that has bothered me about C# since its release was the lack of a generic IsNumeric function. I know it is difficult to generate a one-stop solution to detrmine if a value is numeric.
我已经在过去使用下面的解决方案,但它不是最佳做法,因为我生成一个例外,以确定是否该值则IsNumeric:
I have used the following solution in the past, but it is not the best practice because I am generating an exception to determine if the value is IsNumeric:
public bool IsNumeric(string input)
{
try
{
int.Parse(input);
return true;
}
catch
{
return false;
}
}
这仍然是解决这个问题的最好办法或有没有更有效的方法来确定一个值是在C#中的数值
Is this still the best way to approach this problem or is there a more efficient way to determine if a value is numeric in C#?
推荐答案
试试这个:
int temp;
return int.TryParse(input, out temp);
当然,行为就会从的 Visual Basic中则IsNumeric
。如果你想要的行为,你可以添加引用Microsoft.VisualBasic程序组件,并调用的 Microsoft.VisualBasic.Information.IsNumeric
功能直接。
Of course, the behavior will be different from Visual Basic IsNumeric
. If you want that behavior, you can add a reference to "Microsoft.VisualBasic" assembly and call the Microsoft.VisualBasic.Information.IsNumeric
function directly.
这篇关于缺乏IsNumeric函数的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!