为什么System.Enum是不是值类型? [英] Why System.Enum is not a value-type?

查看:221
本文介绍了为什么System.Enum是不是值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的code的一些测试,输出是出乎我的意料。

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

所以我检查与反射器的 Type.IsValueType 的财产的执行。那就是:

So I check with Reflector the implementation of the Type.IsValueType property. Which is:

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

在MSDN,System.Enum定义为:

In MSDN, System.Enum is defined as:

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

那么,为什么IsValueType implentmented呀?为什么会出现检测enumType?

Then why the IsValueType implentmented that way? Why is there a detection for enumType?

推荐答案

枚举所有从 System.Enum 继承。你不能从一个值类型继承,因此System.Enum不能是值类型。

All enums inherit from System.Enum. You can't inherit from a value type, therefore System.Enum can't be a value type.

这就像 System.ValueType 是不是值类型。这只是一个轻微的古怪其中散发出来的规则的休息。举个这会引起的问题的更具体的例子,借此code:

It's just like System.ValueType isn't a value type. 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;

多少空间应该保留在栈 X 吗?它应该是0字节, System.Enum 本身不具有任何字段(因此截断上分配数据)?它应该是8个字节,以允许最大可能枚举类型?值类型继承基本上导致问题围绕的预期,这就是为什么它被禁止(我相信)。这些理由适用于枚举不亚于其他类型的。

How much space should be reserved on the stack for x? Should it be 0 bytes, as System.Enum itself doesn't have any fields (thus truncating data on assignment)? Should it be 8 bytes to allow for the largest possible enum type? 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.

这篇关于为什么System.Enum是不是值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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