c# - 在 C# 中使用可空类型

标签 c# wpf nullable

我在我的类中定义了 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";

如您所见,在 AmountVatAmount 的值为 null 之前,InvoiceAmount 将始终为 null。我该如何解决这个问题??。一种可能的解决方案是将私有(private)变量 AmountVatAmount 的默认值设置为 0。但是使用此设置,当我将记录添加到 xml 时,AmountInvoiceAmount 的值将输入 0;而如果在这种情况下没有输入任何内容,我想保留 null。

请告诉我如何同时满足这两个条件。 不一定要写代码,一般的可以告诉我

提前致谢!!

最佳答案

你可以写 Amount ?? 0
此代码使用 null-coalescing operator ,其计算结果为其第一个非空操作数。

因此,金额 ?? 0 将评估为 Amount 如果它是非 null 和 0 如果它是 null。

关于c# - 在 C# 中使用可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828996/

相关文章:

wpf - 从 wpf 图像控件中提取图像并将其保存到本地 PCc 上的 png 文件中#

c# - 为什么这些参数不起作用?

kotlin - 使用 Kotlin 在 RxJava 中处理可空类型

c# - 如何在 Entity Framework 中具有映射到可为空的数据库列的值类型?

c# - 监控打印

c# - 如何编辑 mif/mid gis 数据格式?

c# - 如何删除 JSON 字符串中的开始和结束双引号以及所有反斜杠 - C#

c# - SQLDependency with DI

c# - 在标题中使用 '/' 时如何防止列不显示在 WPF 数据网格中?

c# - 如何在列表框中加载所有已知的颜色?