【问题标题】:How do I check if an object exists in an array before setting it’s value in SOAP request?如何在 SOAP 请求中设置对象的值之前检查对象是否存在于数组中?
【发布时间】:2019-05-10 01:57:55
【问题描述】:

这个问题我有一个小的编程问题。下面是一个简单的 SOAP 请求,它接受 3 个参数(itemIDArr、depth、customInfo)。如果 firstName、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.");
  }

这行得通,但问题出现了,因为我必须在消息框中显示名字、surName 和地址,如果我使用 try catch,我将无法访问 try catch 范围之外的值。我该如何做到这一点?

简而言之,我如何首先检查 givenName、surname、street1、city、postalCode、country、numberValue 等是否存在,然后最后将其设置为相应的字符串?

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

【问题讨论】:

    标签: c# soap try-catch


    【解决方案1】:

    这里有一些不清楚的地方,比如 itemSummaryRes 与 entitySummaryRes,以及 entitySummaryRes 中的任何条目是否可以为空。但是……也许只是像这样在里面贴一些“?”:

    string firstName = e.bestName?.givenName; 
    

    还建议您修剪地址,因为例如,如果街道名称为空,则会有一个前导“”。

    【讨论】:

    • 我错误地为 itemSummaryRes 写了 entitySummaryRes。我刚刚修好了。感谢您指出了这一点。坚持“?”工作!非常感谢。
    • 另外,您介意详细说明一下您关于修剪地址的建议吗?
    • 像这样:字符串地址 = (streetName + " " + city + " " + state + " " + country).Trim();
    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多