从任务返回字典<string,string> + CookieContainer cookies

时间:2016-03-03 21:48:51

标签: c# dictionary cookies async-await httpwebrequest

我有一些代码运行一个任务来返回一个字典...但有时我需要它来返回字典和一个带cookie的cookiecontainer ...这里是代码

        static public async Task<Dictionary<String,String>> login(string server, string id, string pw)
    {


        CookieContainer cookies = new CookieContainer();
        HttpWebRequest newRequest = GetNewRequest(server, cookies);
        Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
        dictionary2.Add("name", id);
        dictionary2.Add("password", pw);
        dictionary2.Add("uni_url", server);
        Dictionary<string, string> parameters = dictionary2;
        HttpWebResponse response = await MakeRequest(newRequest, cookies, "login", server, parameters);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            if (!reader.EndOfStream)
            {
                Dictionary<String, String> answer = new Dictionary<string, string>();
                answer.Add("HTML", reader.ReadToEnd());
                return answer;// here i need it to return CookieContainer .
            }
        }
        Dictionary<String, String> answerFailed = new Dictionary<string, string>();
        answerFailed.Add("LoginFailed", "LoginFailed! No Internet Connection!");
        return answerFailed;
    }

我的问题:如何从同一方法中返回两个不同的东西?

2 个答案:

答案 0 :(得分:2)

如果您可以更改方法,则可以使用Tuple<T1,T2>从任务返回两个值:

 static public async Task<Tuple<Dictionary<String,String>,CookieContainer>> login(string server, string id, string pw)
    {
     CookieContainer cookies = new CookieContainer();
      Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
// create result tuple
     var result = Touple.create(dictionary2,cookies);
     return result;
    }

答案 1 :(得分:1)

过载功能无法帮助您,因为只有参数应该不同。

在这些情况下,我通常会创建一个新类,其中包含您需要的所有属性作为输出,并从task返回这些classe的实例。 开销很小,是未来扩张的良好模式。