[英]Working with Nullable types in C#
我在我的類中定義了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";
正如您所看到的,直到Amount或VatAmount的值為null, InvoiceAmount將始終為null。 我該如何解決這個問題? 一種可能的解決方案是將Amount和VatAmount的私有變量的默認值設置為0 。 但是當我將記錄添加到xml時,使用此設置, Amount和InvoiceAmount的值將輸入0; 而如果在這種情況下沒有輸入,我想保留null。
讓我知道如何滿足這兩個條件。 不一定需要編寫代碼,一般可以告訴我
提前致謝 !!
你可以寫Amount ?? 0
Amount ?? 0
。
此代碼使用null-coalescing運算符 ,該運算符計算其第一個非空操作數。
因此, Amount ?? 0
如果它為非空,則Amount ?? 0
將評估為Amount
如果為null,則為0
。
如何在計算中使用Nullable<T>
的GetValueOrDefault
方法? 這樣,您將獲得計算的零,但保留xml的空值。
this.InvoiceAmount = this.Amount.GetValueOrDefault()
+ this.VatAmount.GetValueOrDefault();
if (this.Amount.HasValue)
this.InvoiceAmount += this.Amount;
if (this.VatAmount.HasValue)
this.InvoiceAmount += this.VatAmount;
我認為你必須在add方法中檢查null並將其視為零。
例如:
//HERE I NEED 0 TO PERFORM THE CALCULATION
this.InvoiceAmount = this.Amount ?? decimal.Zero + this.VatAmount ?? decimal.Zero;
return this.InvoiceAmount
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.