自从C#发布以来,困扰我的一件事就是缺少通用的IsNumeric函数。我知道,如果一个值是数值,那么很难生成一站式的解决方案来确定。
我在过去使用过以下解决方案,但这不是最佳实践,因为我正在生成一个异常来确定值是否为IsNumeric:
public bool IsNumeric(string input)
{
try
{
int.Parse(input);
return true;
}
catch
{
return false;
}
}这仍然是解决这个问题的最好方法吗?还是有更有效的方法来确定一个值在C#中是否为数值?
发布于 2010-05-27 06:17:39
试试这个:
int temp;
return int.TryParse(input, out temp);当然,其行为将不同于Visual Basic IsNumeric。如果您想要这种行为,可以添加对"Microsoft.VisualBasic“程序集的引用并直接调用Microsoft.VisualBasic.Information.IsNumeric function。
发布于 2010-05-27 06:21:30
您可以使用extension methods扩展字符串类型,使其包含IsInteger:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool IsInteger(this String input)
{
int temp;
return int.TryParse(input, out temp);
}
}
}发布于 2010-05-27 06:17:30
您可以使用int.TryParse来避免异常,而不是使用int.Parse。
像这样的东西
public static bool IsNumeric(string input)
{
int dummy;
return int.TryParse(input, out dummy);
}更一般的情况下,您可能想看看double.TryParse。
您还应该考虑的一件事是处理不同区域性的数字字符串的可能性。例如,希腊语(el-GR)使用,作为小数分隔符,而UK (en-GB)使用.。因此,字符串"1,000“将是1000或1,具体取决于当前区域性。鉴于此,您可以考虑为支持传递目标区域性、数字格式等的IsNumeric提供重载。看看double.TryParse的2个重载。
https://stackoverflow.com/questions/2917228
复制相似问题