从方法返回值

时间:2013-05-17 09:58:33

标签: c#

我有以下代码:

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

}  

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

4 个答案:

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

答案 1 :(得分: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();
            }
        }
    }
}

答案 2 :(得分: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;
}

答案 3 :(得分:1)

您需要在text中将Send()定义为局部变量,而不是像using(...)里面的子地方块一样。这样只会在那里有效。