2016-03-05 2 views
0

Кажется, я не могу найти ответ в любом месте в Интернете по моей проблеме.Возвращаемое значение из выделенного метода TryParse C#

Я пытаюсь написать метод Int.TryParse в отдельном классе, который может быть вызван всякий раз, когда пользователь вводит ввод. Таким образом, вместо того, чтобы писать это каждый раз есть вход:

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

Im пытается сделать это произошло (от основного метода)

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

Для того, чтобы связывать значение parsed вызывающего метод, вам нужно будет либо в return его или сделать его доступным в качестве out параметра, как int.TryParse() делает.

Возврат значения является самым простым способом, но он не дает способа узнать, удалось ли синтаксический анализ. Однако, если вы измените тип возврата на Nullable<int> (aka int?), вы можете использовать возвращаемое значение null для указания отказа.

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 
Смежные вопросы