What's the best way to do the equivalent of int.TryParse (which is found in .net 2.0 onwards) using .net 1.1.
使用.net 1.1执行等效int.TryParse(在.net 2.0以后找到)的最佳方法是什么。
4 个解决方案
#1
Obviously,
class Int32Util
{
public static bool TryParse(string value, out int result)
{
result = 0;
try
{
result = Int32.Parse(value);
return true;
}
catch(FormatException)
{
return false;
}
catch(OverflowException)
{
return false;
}
}
}
#2
try
{
var i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
#3
Koistya almost had it. No var command in .NET 1.1.
Koistya几乎拥有它。 .NET 1.1中没有var命令。
If I may be so bold:
如果我可能这么大胆:
try
{
int i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
#4
There is a tryparse for double, so if you use that, choose the "NumberStyles.Integer" option and check that the resulting double is within the boundaries of Int32, you can determine if you string is an integer without throwing an exception.
有一个tryparse for double,所以如果你使用它,选择“NumberStyles.Integer”选项并检查生成的double是否在Int32的边界内,你可以确定string是一个整数而不抛出异常。
hope this helps, jamie
杰米希望这有帮助
private bool TryIntParse(string txt)
{
try
{
double dblOut = 0;
if (double.TryParse(txt, System.Globalization.NumberStyles.Integer
, System.Globalization.CultureInfo.CurrentCulture, out dblOut))
{
// determined its an int, now check if its within the Int32 max min
return dblOut > Int32.MinValue && dblOut < Int32.MaxValue;
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
}
}
#1
Obviously,
class Int32Util
{
public static bool TryParse(string value, out int result)
{
result = 0;
try
{
result = Int32.Parse(value);
return true;
}
catch(FormatException)
{
return false;
}
catch(OverflowException)
{
return false;
}
}
}
#2
try
{
var i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
#3
Koistya almost had it. No var command in .NET 1.1.
Koistya几乎拥有它。 .NET 1.1中没有var命令。
If I may be so bold:
如果我可能这么大胆:
try
{
int i = int.Parse(value);
}
catch(FormatException ex)
{
Console.WriteLine("Invalid format.");
}
#4
There is a tryparse for double, so if you use that, choose the "NumberStyles.Integer" option and check that the resulting double is within the boundaries of Int32, you can determine if you string is an integer without throwing an exception.
有一个tryparse for double,所以如果你使用它,选择“NumberStyles.Integer”选项并检查生成的double是否在Int32的边界内,你可以确定string是一个整数而不抛出异常。
hope this helps, jamie
杰米希望这有帮助
private bool TryIntParse(string txt)
{
try
{
double dblOut = 0;
if (double.TryParse(txt, System.Globalization.NumberStyles.Integer
, System.Globalization.CultureInfo.CurrentCulture, out dblOut))
{
// determined its an int, now check if its within the Int32 max min
return dblOut > Int32.MinValue && dblOut < Int32.MaxValue;
}
else
{
return false;
}
}
catch(Exception ex)
{
throw ex;
}
}