繁体   English   中英

在C#中使用Nullable类型

[英]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";

正如您所看到的,直到AmountVatAmount的值为null, InvoiceAmount将始终为null。 我该如何解决这个问题? 一种可能的解决方案是将AmountVatAmount的私有变量的默认值设置为0 但是当我将记录添加到xml时,使用此设置, AmountInvoiceAmount的值将输入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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM