专用TryParse方法的返回值c#

时间:2016-03-05 19:03:20

标签: c# tryparse

我似乎无法在网上找到答案。

我试图在单独的类中编写Int.TryParse方法,只要用户输入,就可以调用它。因此,不是每次写入都有输入:

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

我试图让这种情况发生(来自主要方法)

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;
        }
    }       

    } 

}

为什么我的Variabel" z"获得"解析"的价值程序何时返回值?

1 个答案:

答案 0 :(得分: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