为什么C#限制可以声明为const的类型集合? [英] Why does C# limit the set of types that can be declared as const?

查看:204
本文介绍了为什么C#限制可以声明为const的类型集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器错误 CS0283 表示只有基本的POD类型(以及字符串,枚举和空引用)可以声明为 const 。有没有人有一个理论的这个限制的理由?例如,能够声明其他类型的const值,如IntPtr是很好的。



我相信 const 实际上是C#中的语法糖,它只是用字面值替换了名称的任何使用。例如,给定以下声明,任何对Foo的引用将在编译时被替换为foo。

  const string Foo =foo; 

这将排除任何可变类型,所以也许他们选择了这个限制而不是在编译时确定时间是否给定类型是可变的?

解决方案

C#规范,第10.4章 - 常量

3.0规范,10.3在线版本2.0)




常数是表示常量值的类成员:a


这基本上说,你只能使用只由文字组成的表达式。任何方法,构造函数(不能被表示为纯IL文字)不能被使用,因为编译器没有办法做这个执行,因此在编译时计算结果。另外,由于没有办法标记一个方法作为不变的(即。在输入和输出之间有一对一映射),编译器这样做的唯一方法是分析IL以查看它是否取决于除输入参数之外的事物,特殊情况句柄的一些类型(例如IntPtr),或者只允许每次调用任何代码。



IntPtr虽然是一个值类型,但仍然是一个结构,内置文字。因此,使用IntPtr的任何表达式都需要调用IntPtr结构中的代码,这对于常量声明是不合法的。



唯一的法律常数类型的例子我可以想到的是一个通过只是声明它的零初始化,这是几乎没有用。



对于编译器如何处理/使用常量,将使用计算的值代替代码中的常量名。



因此,您将获得以下效果:




  • 没有对原始常量名称的引用,将它在/或命名空间中声明的类编译到此位置的代码中

  • 如果反编译代码,它会有魔术数字在它,只是因为原来的引用常量是,如上所述,不存在,只有常量的值

  • 编译器可以使用这样可以优化,甚至删除不必要的代码。例如, if(SomeClass.Version == 1),当SomeClass.Version的值为1时,实际上会删除if语句,并保留块代码正在执行。如果常数的值不为1,则整个if语句及其块将被删除。

  • 由于常量的值被编译到代码中,而不是引用如果常数的值应该改变(它不应该!),则使用其他程序集的常量不会自动更新编译的代码。



换句话说,使用以下场景:


  1. 程序集A包含一个名为Version值为1

  2. 程序集B包含一个表达式,用于从该常量分析程序集A的版本号,并将其与1进行比较,以确保它可以与程序集一起使用

  3. 有人修改汇编A,将常数值增加到2,并重建A(但不是B)。

在这种情况下,程序集B以其编译的形式,仍然将1的值与1进行比较,因为当编译B时,常数的值为1.



事实上,如果这是组件B中组件A的唯一用法,组件B将被编译而不依赖于组件A.执行包含组件B中的表达式的代码将不会加载组件A.

因此,常量只能用于永远不会改变的事情。如果它是一个值,将来可能或将改变一些时间,并且您不能保证所有其他程序集同时重建,readonly字段比常数更合适。



这是确定:




  • public const Int32 NumberOfDaysInAWeekInGregorianCalendar = 7;

  • public const Int32 NumberOfHoursInADayOnEarth = 24;



,但这不是:




  • public const Int32 AgeOfProgrammer = 25;

  • public const String NameOfLastProgrammerThatModifiedAssembly =Joe Programmer;


b $ b


编辑2016年5月27日



所以我在这里重新阅读我的答案,这实际上是有点错误。



现在,C#语言规范的意图以上。你不应该使用不能用字面量表示为 const 的东西。



但你能?好的,是的。



让我们来看看十进制类型。

  public class Test 
{
public const decimal Value = 10.123M;
}

让我们看看这个类看起来像当使用ildasm查看时:

  .field public static initonly valuetype [mscorlib] System.Decimal X 
。 void [mscorlib] System.Runtime.CompilerServices.DecimalConstantAttribute ::。ctor(int8,uint8,uint32,uint32,uint32)=(01 00 01 00 00 00 00 00 00 00 00 00 64 00 00 00 00 00)

让我为你分解一下:

  .field public static initonly 

对应于:

  public static readonly 

没错, const decimal 实际上是一个 readonly十进制



这里真正的处理是编译器将使用 DecimalConstantAttribute 来实现它的魔力。



,这是我知道的唯一这样的魔法与C#编译器,但我认为这值得一提。


Compiler error CS0283 indicates that only the basic POD types (as well as strings, enums, and null references) can be declared as const. Does anyone have a theory on the rationale for this limitation? For instance, it would be nice to be able to declare const values of other types, such as IntPtr.

I believe that the concept of const is actually syntactic sugar in C#, and that it just replaces any uses of the name with the literal value. For instance, given the following declaration, any reference to Foo would be replaced with "foo" at compile time.

const string Foo = "foo";

This would rule out any mutable types, so maybe they chose this limitation rather than having to determine at compile time whether a given type is mutable?

解决方案

From the C# specification, chapter 10.4 - Constants:
(10.4 in the C# 3.0 specification, 10.3 in the online version for 2.0)

A constant is a class member that represents a constant value: a value that can be computed at compile time.

This basically says that you can only use expressions that consists solely of literals. Any calls to any methods, constructors (that cannot be represented as pure IL literals) cannot be used, as there is no way for the compiler to do that execution, and thus compute the results, at compile time. Also, since there is no way to tag a method as invariant (ie. there is a one-to-one mapping between input and output), the only way for the compiler to do this would be to either analyze the IL to see if it depends on things other than the input parameters, special-case handle some types (like IntPtr), or just disallow every call to any code.

IntPtr, as an example, though being a value type, is still a structure, and not one of the built-in literals. As such, any expression using an IntPtr will need to call code in the IntPtr structure, and this is what is not legal for a constant declaration.

The only legal constant value type example I can think of would be one that is initialized with zeroes by just declaring it, and that's hardly useful.

As for how the compiler treats/uses constants, it will use the computed value in place of the constant name in the code.

Thus, you have the following effect:

  • No reference to the original constant name, class it was declared in, or namespace, is compiled into the code in this location
  • If you decompile the code, it will have magic numbers in it, simply because the original "reference" to the constant is, as mentioned above, not present, only the value of the constant
  • The compiler can use this to optimize, or even remove, unnecessary code. For instance, if (SomeClass.Version == 1), when SomeClass.Version has the value of 1, will in fact remove the if-statement, and keep the block of code being executed. If the value of the constant is not 1, then the whole if-statement and its block will be removed.
  • Since the value of a constant is compiled into the code, and not a reference to the constant, using constants from other assemblies will not automagically update the compiled code in any way if the value of the constant should change (which it should not!)

In other words, with the following scenario:

  1. Assembly A, contains a constant named "Version", having a value of 1
  2. Assembly B, contains an expression that analyzes the version number of assembly A from that constant and compares it to 1, to make sure it can work with the assembly
  3. Someone modifies assembly A, increasing the value of the constant to 2, and rebuilds A (but not B)

In this case, assembly B, in its compiled form, will still compare the value of 1 to 1, because when B was compiled, the constant had the value 1.

In fact, if that is the only usage of anything from assembly A in assembly B, assembly B will be compiled without a dependency on assembly A. Executing the code containing that expression in assembly B will not load assembly A.

Constants should thus only be used for things that will never change. If it is a value that might or will change some time in the future, and you cannot guarantee that all other assemblies are rebuilt simultaneously, a readonly field is more appropriate than a constant.

So this is ok:

  • public const Int32 NumberOfDaysInAWeekInGregorianCalendar = 7;
  • public const Int32 NumberOfHoursInADayOnEarth = 24;

while this is not:

  • public const Int32 AgeOfProgrammer = 25;
  • public const String NameOfLastProgrammerThatModifiedAssembly = "Joe Programmer";

Edit May 27th 2016

OK, just got an upvote, so I re-read my answer here and this is actually slightly wrong.

Now, the intention of the C# language specification is everything I wrote above. You're not supposed to use something that cannot be represented with a literal as a const.

But can you? Well, yes....

Let's take a look at the decimal type.

public class Test
{
    public const decimal Value = 10.123M;
}

Let's look at what this class looks like really when looked at with ildasm:

.field public static initonly valuetype [mscorlib]System.Decimal X
.custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(int8, uint8, uint32, uint32, uint32) = ( 01 00 01 00 00 00 00 00 00 00 00 00 64 00 00 00 00 00 ) 

Let me break it down for you:

.field public static initonly

corresponds to:

public static readonly

That's right, a const decimal is actually a readonly decimal.

The real deal here is that the compiler will use that DecimalConstantAttribute to work its magic.

Now, this is the only such magic I know of with the C# compiler but I thought it was worth mentioning.

这篇关于为什么C#限制可以声明为const的类型集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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