从方法返回值

本文关键字:返回值 方法 | 更新日期: 2023-09-27 18:14:18

我有以下代码:

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'在当前上下文中不存在。如何从方法中返回'Text'值

从方法返回值

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

必须在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;
}

您需要将text定义为Send()中的局部变量,而不是像using(...)中那样在子局部块中定义。因此,它只在那里有效