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. Which is:
public bool get_IsValueType()
{
return this.IsValueTypeImpl();
}
protected virtual bool IsValueTypeImpl()
{
Type type = this;
return (((type != valueType) && (type != enumType)) &开发者_StackOverflow中文版& this.IsSubclassOf(valueType));
}
In MSDN, System.Enum is defined as:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType, IComparable,
IFormattable, IConvertible
Then why the IsValueType implentmented that way? Why is there a detection for enumType?
All enums inherit from System.Enum
. You can't inherit from a value type, therefore System.Enum can't be a value type.
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;
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.
精彩评论