简体   繁体   English

为什么System.Enum不是值类型?

[英]Why System.Enum is not a value-type?

I write the following code for some test, and the output is out of my expectation. 我编写了以下代码用于某些测试,输出超出了我的预期。

public enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };    
Console.WriteLine(typeof(System.Enum).IsValueType.ToString());   // False
Console.WriteLine(typeof(Days).IsValueType.ToString()); // True

So I check with Reflector the implementation of the Type.IsValueType property. 所以我用Reflector检查Type.IsValueType属性的实现。 Which is: 这是:

public bool get_IsValueType()
{
    return this.IsValueTypeImpl();
}
protected virtual bool IsValueTypeImpl()
{
    Type type = this;
    return (((type != valueType) && (type != enumType)) && this.IsSubclassOf(valueType));
}

In MSDN, System.Enum is defined as: 在MSDN中,System.Enum定义为:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType, IComparable, 
    IFormattable, IConvertible

Then why the IsValueType implentmented that way? 那么为什么IsValueType以这种方式实现呢? Why is there a detection for enumType? 为什么检测到enumType?

All enums inherit from System.Enum . 所有枚举都从System.Enum继承。 You can't inherit from a value type, therefore System.Enum can't be a value type. 您不能从值类型继承,因此System.Enum不能是值类型。

It's just like System.ValueType isn't a value type. 就像System.ValueType不是值类型一样。 It's just a slight oddity which comes out of the rest of the rules. 从其他规则中得出的只是一点点奇怪。 To give a more concrete example of the problems which it would cause, take this code: 为了给出它可能引起的问题的更具体的例子,请使用以下代码:

enum Foo : int { X }
enum Bar : long { Y }

...

Enum x = Foo.X;
x = Bar.Y;

How much space should be reserved on the stack for x ? x的堆栈应该保留多少空间? Should it be 0 bytes, as System.Enum itself doesn't have any fields (thus truncating data on assignment)? 它应该是0字节,因为System.Enum本身没有任何字段(因此在分配时截断数据)? Should it be 8 bytes to allow for the largest possible enum type? 应该是8个字节,以允许最大可能的枚举类型? Value type inheritance basically leads to issues around expectations, which is why it's prohibited (I believe). 价值类型继承基本上导致围绕期望的问题,这就是为什么它被禁止(我相信)。 Those reasons apply to enums as much as to other types. 这些原因适用于枚举和其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM