关于 C# 中常量小数字段的令人困惑的警告

Confusing warning about a constant decimal field in C#

我在探索大量 C# 教程时尝试使用 const 修饰符,并在 class 中放置了一堆 const 修饰符,但实际上没有在任何地方使用它们:

class ConstTesting
{
    const decimal somedecimal = 1;
    const int someint = 2;
    ...
}

使用此 class,我收到以下警告(使用 csc):

ConstTesting.cs(3,19): warning CS0414: The field ‘ConstTesting.somedecimal’ is assigned but its value is never used

我不明白的是 我只收到 const decimal 的警告。 const int 不会给我任何警告,无论顺序如何。

我的问题是,为什么会这样?为什么我的 csc 编译器首先会警告我关于 const,如果它更重要 为什么它只会警告我关于 const decimal当我以完全相同的方式写 const int 时? intdecimal 之间的区别到底与它有什么关系?

请注意:

Int 是一种固定大小的简单值类型。由于比例,小数有点复杂。如果你反编译你的代码,你会发现它看起来像这样:

[DecimalConstant(0, 0, 0, 0, 1)]
private readonly static decimal somedecimal;

private const int someint = 2;

其中 decimal 不是常量,但具有 mscorlib.dll 提供的 DecimalConstant 属性,其中 decimal 的真实定义是:

public struct Decimal : IFormattable, IComparable, IConvertible,
IDeserializationCallback, IComparable<decimal>, IEquatable<decimal>

this blog post 中涵盖了对该主题的更深入探索。