我是C#.Net编程的新手,面临一个问题。当我调用getLocation函数时,我总是将“location”清空。我知道我在做错事。但如果有人能帮助我以正确的方式做到这一点会很棒。我想让getLocation函数返回位置值。因此,只有在返回位置值之前执行wc.downloadString时才会返回。
public String getLocation()
{
RetrieveFormatedAddress(latitude, longitutde);
location = returnVal;
return location;
}
static void RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadString(new Uri(requestUri));
//wc.DownloadStringAsync(new Uri(requestUri));
}
}
private static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
returnVal = res.Value;
}
else
{
returnVal = "No Address Found";
}
}
答案 0 :(得分:2)
public String getLocation()
{
return RetrieveFormatedAddress(latitude, longitutde);
}
static string RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
var result = wc.DownloadString(new Uri(requestUri));
var xmlElm = XElement.Parse(result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
return res.Value;
}
else
{
return "No Address Found";
}
}
}
答案 1 :(得分:1)
DownloadString()
方法是DownloadStringAsync()
方法的同步版本。它将从服务器下载的数据作为字符串返回。在您的代码中,您无法在任何地方读取此值。请尝试var data = wc.DownloadString(new Uri(requestUri));
获取数据。