1

Ok right now I have an object containing 3 strings, along with setters and getters. Now I have two questions -

First, I'm new to C# is there any way to optimize the following methods and make them more efficient?

    void getSearchResults(object sender, RoutedEventArgs e)
    {
        string baseURL = "http://api.search.live.net/xml.aspx?Appid=<MyAPPID>&query=%22";
        string companyName = ((TaxiCompany)sender).CoName;
        string formatAndKey = "%22&sources=web";
        WebClient c = new WebClient();
        c.DownloadStringAsync(new Uri(baseURL + companyName + formatAndKey));
        c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(findTotalResults);
    }


    //Parses search XML result to find number of results
    void findTotalResults(object sender, DownloadStringCompletedEventArgs e)
    {
        lock (this)
        {
            string s = e.Result;
            XmlReader reader = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(s)));
            String results = "";
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name.Equals("web:Total"))
                    {
                        results = reader.ReadInnerXml();
                        break;
                    }

                }
            }
        }
    }

Second, I'm initializing an object - new Taxi Company (String name, String Phone, String Results). I've got name and number and I need to call the above two functions to get noOfResults so that I can initialize the object. However, I seem to run into a bunch of issues with the event handlers.

I've primarily been a web dev, so there might be something really basic I'm missing here. I have a feeling setting up the bing methods to return a string back to the constructor might be th easiest, but not quite sure how.

4

1 回答 1

1

首先,您不需要主页上的锁。然后,我会说您的 XmlReader 块应该替换为称为XDocument的 LINQ-to-XML 变体,这将允许您使用单个优雅的行访问 XML 文档:

XDocument doc = XDocument.Parse(e.Result);

获得文档后,您可以检查它是否包含特定的XNode

于 2010-11-20T20:12:32.403 回答