我看过一个 C# struct FooStruct
在 ILDASM ,并且已经看到以下内容:
ILDASM 在这里显示两个不同的声明:
.class
开头的 value
public
(后窗和前窗的标题栏).class public
开头的(前窗)我想知道哪种语法(如果不是两种)是声明值类型的正确语法?是
value
修饰符是绝对必要的,还是可选的,还是语法错误?
最佳答案
Short answer: Value type definitions only require
extends [mscorlib]System.ValueType
; thevalue
attribute appears to be optional and has no apparent effect.
我认为 CLI 规范 ( ECMA-335 ) 将是寻找权威答案的最佳场所。
值类型定义必须包括
value
属性?第 II.10 节涉及定义类型。更具体地说,第 II.10.1.3 小节指出:
The type semantic attributes specify whether an interface, class, or value type shall be defined. … If [the
interface
] attribute is not present and the definition extends (directly or indirectly)System.ValueType
, and the definition is not forSystem.Enum
, a value type shall be defined (§II.13). Otherwise, a class shall be defined (§II.11).
value
整个部分根本没有提到属性。结论:正确的值类型定义不必包含
value
.源自 System.ValueType
足够了。值类型定义可以包括
value
修饰符?CLI 标准还包含 ILASM 的语法(在第 VI.C.3 节中)。根据那个语法,存在一个
value
.class
的属性类型定义。我还搜索了具体值类型定义的标准,并找到了以下示例:.class public sequential ansi serializable sealed beforefieldinit System.Double extends System.ValueType …
.class private sealed Rational extends [mscorlib]System.ValueType …
.class
value
sealed public MyClass extends [mscorlib]System.ValueType …
结论:一个
value
属性可以包含在值类型定义中。什么是
value
属性平均值?我试图将这三个 IL 类型定义编译成一个程序集:
.class public sealed … A extends [mscorlib]System.ValueType { … }
.class value public sealed … B extends [mscorlib]System.ValueType { … }
.class value public sealed … C extends [mscorlib]System.Object { … } // !!!
没有编译错误,即使
value
属性用于引用类型声明(见最后一行)。使用 Visual Studio 2012 的对象浏览器查看生成的程序集会发现两种值类型 ( struct
) A
和 B
, 和一种引用类型 ( class
) C
.推测:
value
的存在属性对类型定义没有任何影响。它只是作为人类发现值类型定义的潜在帮助。
关于syntax - 如何在 CIL : `.class value` or just `.class` ? 中声明值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026065/