我在我的类中定义了 Nullable 属性,这些属性参与计算和 xml 编写。众所周知,当任何空值参与计算时,结果始终为空。我将通过示例来解释它::
属性和计算代码:
public decimal? Amount { get; set; }
public decimal? VatAmount { get; set; }
public decimal? InvoiceAmount { get; set; }
.
.
public decimal Add()
{
//HERE I NEED 0 TO PERFORM THE CALCULATION
this.InvoiceAmount = this.Amount + this.VatAmount;
return this.InvoiceAmount
}
.
.
public string Insert()
{
XDocument doc1 = XDocument.Load(@"Transactions.xml");
var record = from r in doc1.Descendants("Transaction")
where (int)r.Element("Serial") == Serial
select r;
foreach (XElement r in record)
{
//HERE I WANT NULL VALUES RETAINED
r.Element("DebitNote").Add(new XElement("InvoiceAmount", this.InvoiceAmount), new XElement("VatAmount", this.VatAmount), new XElement("Amount", this.Amount));
}
doc2.Save(@"Transactions.xml");
return "Invoice Created Successfully";
如您所见,在 Amount 或 VatAmount 的值为 null 之前,InvoiceAmount 将始终为 null。我该如何解决这个问题??。一种可能的解决方案是将私有(private)变量 Amount 和 VatAmount 的默认值设置为 0。但是使用此设置,当我将记录添加到 xml 时,Amount 和 InvoiceAmount 的值将输入 0;而如果在这种情况下没有输入任何内容,我想保留 null。
请告诉我如何同时满足这两个条件。 不一定要写代码,一般的可以告诉我
提前致谢!!
最佳答案
你可以写 Amount ?? 0
。
此代码使用 null-coalescing operator ,其计算结果为其第一个非空操作数。
因此,金额 ?? 0
将评估为 Amount
如果它是非 null 和 0
如果它是 null。
关于c# - 在 C# 中使用可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828996/