c# - decimal 和 decimal 上的空合并运算符

标签 c# null operator-keyword coalescing

我在应用空合并运算符时遇到以下错误。

private decimal _currentImpulseId;
// ... later on used in public property getter as follows

public decimal CurrentImpulseId
{
  get { return _currentImpulseId ?? 0M; }
  set { _currentImpulseId = value; }
}

返回以下错误:

Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'

为什么这行不通?空合并运算符是否不适用于小数,或者我在这里遗漏了什么?我知道如何在不使用运算符的情况下解决这个问题,但这让我有些困惑,所以我想知道你是否知道这方面的正确答案?

谢谢!

最佳答案

您收到此错误是因为 decimal 是一个值类型,而不是可为 null 的值类型(例如 decimal?)或引用类型。

来自 MSDN :

...and is used to define a default value for nullable value types or reference types

decimal 类型变量的默认值为零,所以我不太确定您为什么要在这种情况下使用此运算符。

此外,自从引入 auto-implemented properties 以来,自 .NET 3.0 起不需要支持字段变量 (_currentImpulseId)意味着你可以写

public decimal CurrentImpulseId { get; set; }

关于c# - decimal 和 decimal 上的空合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12072553/

相关文章:

windows - FIND 命令返回空值

null - express + express-graphql helloworld 返回 null

c++ - 为什么在模板中调用基类的运算符?

c# - ASP.NET c# 中的 AJAX 错误

c# - 无法附加分离的实体(具有相同键的实体已经在上下文中)

c# - Entity Framework 错误 : Cannot insert explicit value for identity column in table

c++ - 如何使用数组重载 ostream 运算符<<?

javascript - 在同一个 MVC 项目中的 C# 类和 JS 文件中使用相同的静态数据,而无需在运行时一次又一次地重建

mysql - 如果计数为 0,则显示 Null

c++ - 模板化类中的关系运算符重载 (C++)