Decimal.MinValue&Decimal.MaxValue:为什么静态只读而不是const修饰符?

Fab*_*nay 7 static types const numeric readonly

在C#中,MinValue字段是为数字类型定义的:

① 十进制类型的静态只读修饰符(链接到MSDN Libray for .NET 4.5):

public static readonly decimal MinValue
Run Code Online (Sandbox Code Playgroud)

② 所有其他数字类型的const修饰符:

//Integral signed numeric types
public const sbyte MinValue
public const short MinValue
public const int MinValue
public const long MinValue

//Integral unsigned numeric types
public const byte MinValue
public const ushort MinValue
public const uint MinValue
public const ulong MinValue

//Real numeric types
public const float MinValue
public const double MinValue
Run Code Online (Sandbox Code Playgroud)

为什么const修饰符不用于定义Decimal.MinValue字段?

备注:

①同样的问题适用于数值类型MaxValue字段.

②VB,C++和F#也对十进制类型使用不同的修饰符,因此这个问题不是特定于C#语言.

Fab*_*nay 1

尽管MSDN 库将十进制MinValue字段描述为static readonly,但 C# 编译器将其视为const

\n\n

如果MinValue字段是只读的,下面的代码将无法编译,但它实际上可以编译

\n\n

const decimal test = decimal.MinValue - decimal.MinValue;

\n\n

评论

\n\n

\xe2\x91\xa0 相同的答案适用于十进制类型MaxValue字段。

\n\n

\xe2\x91\xa1 有关更多详细信息,Jon Skeet在这里深入介绍了 IL 级别的常量字段实现之间的差异:

\n\n
    \n
  • 原始数字类型(积分、浮点和双精度)和
  • \n
  • 非原始数字十进制类型。
  • \n
\n