2013-05-17 2 views
2

У меня есть следующий код:Возвращение значения из метода

public class Request 
{ 
    static string username = "[email protected]"; 

    public string Send() 
    { 
     ///some variables   

     try 
     { 
      /// 
     } 

     catch (WebException e) 
     { 
      using (WebResponse response = e.Response) 
      { 
       HttpWebResponse httpResponse = (HttpWebResponse)response; 
       Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 
       using (Stream Data = response.GetResponseStream()) 
       { 
        string text = new StreamReader(Data).ReadToEnd();     
       } 
      } 
     } 
     return text; 
    } 

} 

Getting ошибку: «текст» делает т существует в текущем контексте. Как вернуть значение «Текст» из метода.

+1

, потому что это объявить в 'catch' преградить рамки не входит в рамки метода .. –

ответ

4
public string Send() 
{ 
    //define the variable outside of try catch 
    string text = null; //Define at method scope 
    ///some variables   
    try 
    { 
     /// 
    } 

    catch (WebException e) 
    { 
     using (WebResponse response = e.Response) 
     { 
      HttpWebResponse httpResponse = (HttpWebResponse)response; 
      Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 
      using (Stream Data = response.GetResponseStream()) 
      { 
       text = new StreamReader(Data).ReadToEnd(); 
      } 
     } 
    } 
    return text; 
} 
+4

форматирование кода увеличит ответ полезность –

+0

Я согласен с вами, ребята. благодаря –

1

Вы должны инициализировать переменную перед try clause, чтобы использовать его вне try:

public string Send() 
{ 
    string text = null; 

    try 
    { 

    } 
    catch (WebException e) 
    { 
     using (WebResponse response = e.Response) 
     { 
      HttpWebResponse httpResponse = (HttpWebResponse)response; 
      Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 
      using (Stream Data = response.GetResponseStream()) 
      { 
       text = new StreamReader(Data).ReadToEnd(); 
      } 
     } 
    } 

    return text; 
} 
1

Вам нужно определить text в качестве локальной переменной в Send(), а не внутри sublocal блока, как здесь внутри using(...). Это было бы справедливо только там.

2
public string Send() 
{ 
    try { 
     return "Your string value"; 
    } 

    catch (WebException e) { 
     using (WebResponse response = e.Response) { 
      HttpWebResponse httpResponse = (HttpWebResponse)response; 
      Console.WriteLine("Error code: {0}", httpResponse.StatusCode); 
      using (Stream Data = response.GetResponseStream()) 
      { 
       return new StreamReader(Data).ReadToEnd(); 
      } 
     } 
    } 
} 
Смежные вопросы