在设置SOAP请求中的值之前,如何检查对象是否存在于数组中?

时间:2019-05-10 01:57:56

标签: c# soap try-catch

我有一个关于此问题的小编程问题。下面是一个简单的SOAP请求,其中包含3个参数(itemIDArr,depth,customInfo)。如果firstID,surName,streetName…(上面提到的所有值)都存在于itemIDArr中,则该程序可以正常工作。否则给我一个错误。

private void getItemSummary(long itemID)
 {
       //Create client
     MYAPI.ResolvingClient resol = new MYAPI.ResolvingClient();

      //Create parameters
     MYAPI.ItemID[] itemIDArr = new MYAPI.Item [1];
     MYAPI.ItemID itemIDunit = new MYAPI.ItemID();
     itemIDunit.itemID = itemID;
     itemIDArr[0] = itemIDunit;  //param 1
     MYAPI.DepthSpecifier depth = new MYAPI.DepthSpecifier(); //param 2
     MYAPI.CustomInformation customInfo = new MYAPI.CustomInformation(); //param 3

      //Make request
     MYAPI.ItemSummary[] itemSummaryRes = resol.getItemSummaries(itemIDArr, depth, customInfo);

      //Handle response   
          foreach (MYAPI.ItemSummary e in itemSummaryRes)
          {
              string firstName = e.bestName.givenName;                
              string surName = e.bestName.surname;
              string streetName = e.bestAddress.street1;
              string city = e.bestAddress.city;
              string state = e.bestAddress.state;
              string country = e.bestAddress.country;
              string address = streetName + " " + city + " " + state + " " + country;
              string email = e.bestEmail.emailAddress;
              string number = e.bestNumber.numberValue;
              MessageBox.Show(firstName + " " + surName + ", " + address);
         }
  }

在这里,我的问题是在像上面那样分配firstName,surName,streetName等值之前,我需要检查它们是否存在于itemIDArr中。我尝试通过以下方式对所有值使用try catch块:

try
  {
       string firstName = e.bestName.givenName;
  }
  catch (Exception)
  {
      Console.WriteLine("Value of first Name does not exist.");
  }

这有效,但是出现了问题,因为我必须在消息框中显示firstName,surName和address,如果我使用try catch,则无法访问try catch范围之外的值。我该如何完成?

简而言之,我该如何首先检查是否存在namedName,姓氏,street1,城市,postalCode,国家/地区,numberValue等,然后最后将其分别设置为它的字符串?

任何帮助将不胜感激!如果问题仍然不清楚,请告诉我。

1 个答案:

答案 0 :(得分:0)

这里有些不清楚的地方,例如itemSummaryRes和EntitySummaryRes,以及EntitySummaryRes中的任何条目是否可以为空。但是……也许只是在其中贴上一些“?”:

string firstName = e.bestName?.givenName; 

还建议您修剪地址,因为例如,如果街道名称为空,则将以“”开头。

相关问题