c# - 从方法返回值

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

}  

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

最佳答案

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

关于c# - 从方法返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606288/

相关文章:

c# - 给定一个类型对象,为什么我需要使用反射来实例化一个泛型?

c# - 检查 Task.Run 尚未运行

c# - 当匿名用户调用时,Web 服务无法写入事件日志

c# - 附加到序列化集合

c# - 使用c#从mysql返回两个值

c# - 如果 IEnumerable<string> 只返回一个字符串怎么办

c# - 减去列表C#中的相邻两个值

c# - 在 asp.net 中保留枚举值

c# - 使用 TextFieldParser 时如何跳过格式错误的行?

c# - 从 asp.net c# 设置 style.display