2016-03-05 58 views
0

我似乎無法找到答案在任何地方在線我的問題。從專門的TryParse方法返回值c#

我想寫一個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」是否得到「parsed」的值?

回答

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