这是我的代码。我使用该函数来检索列表但不发送它。
public List<string> country_set()
{
mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country");
mList = new List<string> ();
mCountry = new List<Country> ();
WebClient client = new WebClient ();
client.DownloadDataAsync (mCountryUrl);
client.DownloadDataCompleted += (sender, e) => {
RunOnUiThread (() => {
string json = Encoding.UTF8.GetString (e.Result);
mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json);
Console.WriteLine (mCountry.Count.ToString());
int x = mCountry.Count;
for(int i=0; i< x ; i++)
{
mList.Add(mCountry[i].name);
}
});
};
return mList;
}
它会引发异常。 请帮助我
答案 0 :(得分:1)
问题是您在方法完成后立即返回mList,这是在Web服务器调用完成之前。现在,在您的调用代码检查列表以查找它为空之后,最终对服务器的调用将完成,您的列表将被填充,这已经太晚了!
这将解决问题:
var mCountryUrl = new Uri("http://xxxxxxx.wwww/restservice/country");
var mList = new List<string>();
var mCountry = new List<Country>();
WebClient client = new WebClient();
var data = client.DownloadData(mCountryUrl);
string json = Encoding.UTF8.GetString(data);
mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>>(json);
Console.WriteLine(mCountry.Count.ToString());
int x = mCountry.Count;
for (int i = 0; i < x; i++)
{
mList.Add(mCountry[i].name);
}
return mList;
答案 1 :(得分:1)
这个怎么样:
public async Task<List<string>> country_set()
{
mCountryUrl = new Uri ("http://xxxxxxx.wwww/restservice/country");
mList = new List<string>();
mCountry = new List<Country>();
WebClient client = new WebClient();
byte[] data = await client.DownloadDataTaskAsync(mCountryUrl);
string json = Encoding.UTF8.GetString(data);
mCountry = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (json);
Console.WriteLine (mCountry.Count.ToString());
int x = mCountry.Count;
for(int i=0; i<x; i++)
mList.Add(mCountry[i].name);
return mList;
}
它使用.Net的新异步模型。
编辑:代码是从Android应用中输入的。任何发现语法错误(或任何其他类型)的人,请在评论中发出信号。