Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
我有一个名为GetSuggestedAddresses的函数,其中一部分调用了一个返回列表的函数。我的课上还有一个属性,类型为List。我尝试使用AddRange将返回的结果添加到我的属性中,但是它引发了null异常。我尝试单步执行代码,但是有点迷茫。有任何想法吗?这是我的代码-

 public List<ExpressAddressResult> GetSuggestedAddresses(string format = "xml")
  {
     foreach (RequestArrayRecord address in reqRecords) {
        string result = string.Empty;
        NameValueCollection collection = new NameValueCollection();
        collection.Add("id", AuthKey);
        collection.Add("line1", CleanUpAddress(address.AddressLine1));
        collection.Add("city", address.City);
        collection.Add("state", address.State);
        collection.Add("postalcode", address.Zip);
        collection.Add("maxrecords", MaxSuggestionResults.ToString());
        collection.Add("format", format);
        string parameters = GenerateParameters(collection);

        Uri serviceAddress = new Uri(RequestURL + parameters);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
           if (response != null) {
              using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) {
                 result = streamReader.ReadToEnd();
              }
           }
        }

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(result);

        List<ExpressAddressResult> results = CreateListFromXml(xmlDoc);

        if (results != null) {
           AddressSuggestions.AddRange(results); // Throws Null Exception
        }
     }

     return AddressSuggestions; // This is a property of type List<ExpressAddressResult>
  }

最佳答案

var addressSuggestions = new List<ExpressAddressResult>();


虽然我认为您只想返回结果。.它已转换为预期的类型。忘了addRange

关于c# - AddRange引发null异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38508663/

10-13 07:39