我在我的类中定义了Nullable属性,它们参与计算和xml编写.众所周知,当任何空值参与计算时,结果始终为null.我将通过考试解释::
属性和计算代码:
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";
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,直到Amount或VatAmount的值为null,InvoiceAmount将始终为null.我该如何解决这个问题?一种可能的解决方案是将Amount和VatAmount的私有变量的默认值设置为0.但是当我将记录添加到xml时,使用此设置,Amount和InvoiceAmount的值将输入0; 而如果在这种情况下没有输入,我想保留null.
让我知道如何满足这两个条件.不一定需要编写代码,一般可以告诉我
提前致谢 !!
你可以写Amount ?? 0.
此代码使用null-coalescing运算符,该运算符计算其第一个非空操作数.
因此,Amount ?? 0将评估Amount它是否为非null且0是否为null.
如何使用计算中的GetValueOrDefault方法Nullable<T>?这样,您将获得计算的零,但保留xml的空值.
this.InvoiceAmount = this.Amount.GetValueOrDefault()
+ this.VatAmount.GetValueOrDefault();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
778 次 |
| 最近记录: |