代码之家  ›  专栏  ›  技术社区  ›  Matthew Dresser

对于.net 1.1,int.TryParse的最佳替代方案是什么

  •  7
  • Matthew Dresser  · 技术社区  · 16 年前

    使用.NET1.1实现int.TryParse(在.NET2.0以后的版本中可以找到)的最佳方法是什么。

    4 回复  |  直到 16 年前
        1
  •  12
  •   Anton Gogolev    14 年前

    明显地

    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
  •  3
  •   Konstantin Tarkus    16 年前
    try
    {
        var i = int.Parse(value);
    }
    catch(FormatException ex)
    {
        Console.WriteLine("Invalid format.");
    }
    
        3
  •  1
  •   ray    14 年前

    Koistya差点就得了。.NET1.1中没有var命令。

    请允许我大胆一点:

    try
    {
        int i = int.Parse(value);
    }
    catch(FormatException ex)
    {
        Console.WriteLine("Invalid format.");
    }
    
        4
  •  1
  •   Darren user513543    13 年前

    double有一个tryparse,因此如果使用它,请选择“NumberStyles.Integer”选项并检查结果double是否在Int32的边界内,您可以确定字符串是否为整数,而不会引发异常。

    希望这有帮助, 杰米

    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;
        }
    }
    
    推荐文章