在对象资源库中处理空对象
本文关键字:对象 处理 资源库 | 更新日期: 2023-09-27 17:55:26
>我正在尝试使用一个不错的近对象设置器,但有空问题。
我现在的代码:
var Result = new RefundReplyObject
{
AuthorisationNumber = reply.refundResponse.transactionDetails.authorisationNumber,
ChargeValue = reply.refundResponse.transactionDetails.totalAmount.amount,
Message = reply.refundResponse.transactionDetails.message,
ReconciliationReference = reply.refundResponse.transactionDetails.reconciliationReference,
SettlementDate = reply.refundResponse.transactionDetails.settlementDate,
Status = TransactionStatusToLocalModel(reply.refundResponse.transactionDetails.status),
TransactionReference = reply.refundResponse.transactionDetails.transactionReference
};
但。。。"总金额"可能为空。所以,我得到错误。
有没有一种巧妙的方法来解决这个问题,这样如果"totalAmount"为空,则将电荷值设置为零?
三元运算符怎么样,它检查总金额是否为空。如果不是,则使用它amount
,否则为 0。
ChargeValue = (reply.refundResponse.transactionDetails.totalAmount != null) ? reply.refundResponse.transactionDetails.totalAmount.amount : 0,
你可以这样做,例如:
ChargeValue = reply.refundResponse.transactionDetails.totalAmount != null ? reply.refundResponse.transactionDetails.totalAmount.amount : 0
三元运算符来救援!
ChargeValue = totalAmount ? totalAmount.amount : 0;
像这样的东西?
ChargeValue = (null == reply.refundResponse.transactionDetails.totalAmount)
? 0
: reply.refundResponse.transactionDetails.totalAmount.amount
你将无法在事情的二传手方面做到这一点,因为异常甚至在你到达那里之前就发生了。你可以通过做这样的事情来获得你想要的东西(并在此过程中大量清理你的代码):
var trans = reply.refundResponse.transactionDetails;
var Result = new RefundReplyObject
{
AuthorisationNumber = trans.authorisationNumber,
ChargeValue = trans.totalAmount == null ? 0 : trans.totalAmount.amount,
Message = trans.message,
ReconciliationReference = trans.reconciliationReference,
SettlementDate = trans.settlementDate,
Status = TransactionStatusToLocalModeltrans.status),
TransactionReference = trans.transactionReference
};