0

我是 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";
    }

}
4

2 回答 2

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";
        }
    }
}
于 2013-02-15T20:56:33.273 回答
1

DownloadString()方法是方法的同步版本DownloadStringAsync()。它将从服务器下载的数据作为字符串返回。在您的代码中,您不会在任何地方读取此值。尝试var data = wc.DownloadString(new Uri(requestUri));获取数据。

于 2013-02-15T20:58:24.863 回答