常量不能标记静 [英] The constant cannot be marked static

查看:173
本文介绍了常量不能标记静的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明像这样的PI常数:

 公共静态常量双PI = Math.PI; 



但为什么我收到此错误?



 常量'Calendar.NewCalendar.PI'不能标记静态


解决方案

常量意味着静态(你不需要一个实例引用常量值)。



我也想加入这个重要的一点:当您使用公共常量连结反对(参考)组装 ,该值的复制到您的装配。因此,如果在引用的程序集的变化常量价值,你的程序集将仍然有原来编译的值。



如果这种行为的的可以接受的,那么你应该考虑该领域的公共静态只读字段。



Lib.dll,二进制提供的:

 公共类Foo {
酒店的公共const int的HATS = 42;
公共静态只读INT手套= 33;
}

APP.EXE,引用Lib.dll:

  Foo.HATS //这将永远是42即使Lib.dll变化,
值//除非APP.EXE重新编译。

Foo.GLOVES //这将始终是相同的如Lib.dll


$ Foo.GLOVES b $ b







不要创建一个常数来表示你希望在任何时候更改信息。例如,不使用常数域,存储服务,产品版本号,或者一个公司的品牌名称的价格。这些值可随时间而改变,并且因为编译器传播常量,与库编译其他代码将不得不被重新编译以查看更改




通过 DotNetPerls




的DLL 。当您使用常量字段或声明,C#编译器实际上嵌入常量变量的直接价值的IL代码。因此,它本质上擦除常量作为一个独立的实体。



注意:
如果依赖程序在常量未在常量后重新编译值发生变化,它们可能会破坏[,因为它们将继续使用前值的。



I am trying to declare a PI constant like this:

public static const double PI = Math.PI;

but why am I getting this error?

The constant 'Calendar.NewCalendar.PI' cannot be marked static

解决方案

const implies static (you don't need an instance to reference the const value).

I want to also add this important point: When you link against (reference) an assembly with a public const, that value is copied into your assembly. So if the const value in the referenced assembly changes, your assembly will still have the originally compiled-in value.

If this behavior is not acceptable, then you should consider making the field a public static readonly field.

Lib.dll, provided as binary:

public class Foo {
    public const int HATS = 42;
    public static readonly int GLOVES = 33;
}

App.exe, references Lib.dll:

Foo.HATS    // This will always be 42 even if the value in Lib.dll changes,
            // unless App.exe is recompiled.

Foo.GLOVES  // This will always be the same as Foo.GLOVES in Lib.dll


From MSDN:

Don’t create a constant to represent information that you expect to change at any time. For example, don’t use a constant field to store the price of a service, a product version number, or the brand name of a company. These values can change over time, and because compilers propagate constants, other code compiled with your libraries will have to be recompiled to see the changes.

From DotNetPerls:

DLLs. When you use a const field or declaration, the C# compiler actually embeds the const variable's value directly in the IL code. Therefore, it essentially erases the const as a separate entity.

Caution: If programs that depend on a const are not recompiled after the const value changes, they may break [because they'll continue to use the previous value].

这篇关于常量不能标记静的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆