2

我有以下代码:

public class Request
{
    static string username = "ha@gmail.com";

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

}  

出现错误:当前上下文中不存在“文本”。如何从方法中返回“文本”值。

4

4 回答 4

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;
}
于 2013-05-17T10:00:26.787 回答
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();
            }
        }
    }
}
于 2013-05-17T10:08:00.490 回答
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;
}
于 2013-05-17T10:00:16.967 回答
1

您需要定义text为 in 中的局部变量Send(),而不是像 here inside 那样的子局部块内部using(...)。这样它只会在那里有效。

于 2013-05-17T10:00:36.427 回答