【问题标题】:Return value from dedicated TryParse Method c#来自专用 TryParse 方法的返回值 c#
【发布时间】:2016-03-05 19:03:19
【问题描述】:

我似乎无法在网上任何地方找到我的问题的答案。

我正在尝试在单独的类中编写Int.TryParse 方法,只要用户进行输入,就可以调用该方法。所以不是每次有输入时都写这个:

    int z;
    int.TryParse(Console.writeLine(), out z);

我正在尝试实现这一点(来自 main 方法)

int z; 
Console.WriteLine("What alternative?");   
Try.Input(Console.ReadLine(), z); // sends the input to my TryParse method

tryparse 方法

 class Try
    {

    public static void Input(string s, int parsed)
    {
        bool Converted = int.TryParse(s, out parsed);

        if (Converted)      // Converted = true
        {
            return;                
        }
        else                //converted = false
        {
            Console.Clear();
            Console.WriteLine("\n{0}: Is not a number.\n\nPress ENTER to return", s);
            Console.ReadLine();
            return;
        }
    }       

    } 

}

当程序返回值时,为什么我的变量“z”会得到“已解析”的值?

【问题讨论】:

    标签: c# tryparse


    【解决方案1】:

    为了将parsed 值传递给调用方法,您需要return 或将其作为out 参数提供,就像int.TryParse() 一样。

    返回值是最直接的方法,但它没有提供知道解析是否成功的方法。但是,如果您将返回类型更改为Nullable<int>(又名int?),那么您可以使用空返回值来指示失败。

    public static int? Input(string s)
    {
        int parsed;
        bool Converted = int.TryParse(s, out parsed);
    
        if (Converted)      // Converted = true
        {
            return null;                
        }
        else                //converted = false
        {
            Console.Clear();
            Console.WriteLine("\n{0}: Is not a number.\n\nPress ENTER to return", s);
            Console.ReadLine();
            return parsed;
        }
    }      
    
    
    Console.WriteLine("What alternative?");   
    int? result = Try.Input(Console.ReadLine()); 
    if(result == null)
    {
        return;
    }
    // otherwise, do something with result.Value
    

    使用out 参数将反映int.TryParse() 方法签名:

    public static bool Input(string s, out int parsed)
    {
        bool Converted = int.TryParse(s, out parsed);
    
        if (Converted)      // Converted = true
        {
            return false;                
        }
        else                //converted = false
        {
            Console.Clear();
            Console.WriteLine("\n{0}: Is not a number.\n\nPress ENTER to return", s);
            Console.ReadLine();
            return true;
        }
    }       
    
    Console.WriteLine("What alternative?");   
    int z;
    if(!Try.Input(Console.ReadLine(), out z))
    {
        return;
    }
    // otherwise, do something with z
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多