gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:04:06 27 4
gpt4 key购买 nike

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

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

对于此类,我收到以下警告(使用 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 之间的区别到底与它有什么关系?

请注意:

    - 我没有 ReSharper
    - 我正在使用 VS 2010
    - 我 100% 确定我的代码中的任何地方都没有使用 `const`。

最佳答案

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 中涵盖了对该主题的更深入探索。 .

关于c# - 关于 C# 中常量小数字段的令人困惑的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28492204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com