① 对于十进制类型,使用static readonly修饰符 (链接到.NET 4.5的MSDN库):
public static readonly decimal MinValue
② 对于所有其他数值类型,使用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
为什么不使用“const”修饰符来定义Decimal.MinValue字段?
备注:
① 同样的问题也适用于数值类型的MaxValue字段。
② VB、C++和F#也使用不同的修饰符来定义十进制类型,因此这个问题并不特定于C#语言。
Decimal
不像其他类型那样原始。 - Mark HurdDecimal
结构体的MinValue
字段是一个const
并且像一个常量一样运作。如果您使用 Visual Studio 并在decimal
上使用“转到定义”(F12),则会看到“元数据”(通过反射从实际程序集生成的 C# 代码)显示[DecimalConstant(0, 128, 4294967295, 4294967295, 4294967295)] public const decimal MinValue = -79228162514264337593543950335m;
。因此,MinValue
的作用类似于一个常量。您可以从它声明其他const
值,将其用作可选参数的默认值等。 - Jeppe Stig Nielsendecimal
是语言中的预定义类型,它是C#中所谓的简单类型,详见4.1值类型和4.1.4简单类型(这里我链接了旧版本的规范,但最新版本也是一样的)。而且C#允许所有这些“简单类型”,包括decimal
,使用const
字段。现在当mscorlib包含一个“预定义类型”的源代码时,可能需要一些技巧。 - Jeppe Stig Nielsen