我在应用空合并运算符时遇到以下错误。
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/