我是 C#.Net 编程的新手并面临一个问题。当我调用 getLocation 函数时,我总是将“位置”设为空。我知道我做事的方式不对。但是,如果有人可以帮助我以正确的方式做到这一点,那就太好了。我希望 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";
}
}