为什么我不能从System

为什么我不能从System

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

问题描述

限时删除!!

MSDN System.Enum定义为抽象类:

  [SerializableAttribute]
[ComVisibleAttribute(真)
公共抽象类枚举:值类型,IComparable的,IFormattable,IConvertible
 

和MSDN也做出抽象类这样的语句:

但我根本无法从System.Enum派生。据杰弗里里氏在其著作CLR通过C#,它是C#编译器禁止的推导。

和我检查System.Enum成员,他们大多是静态的,这是合理的,它不能被实例化和静态方法不需要一个对象实例来调用。但是,也有一些实例方法,这样的GetHash code()和的GetType code()。

 公开枚举天:字节{周六,周日,周一,周二,周三,周四,周五};
天D = Days.Friday;
d.GetType code();
d.GetHash code();
 

解决方案

可以从枚举,例如:

导出

 公开枚举MyEnum
{
    // ...
}
 

将被编译到是这样的:

 的.class众汽车ANSI密封MyEnum
    扩展System.Enum
{
    // ...
}
 

中限制使用C#编译器的地方是,它不会让你手动编写的推导,而是要求你使用枚举关键字在声明的类型。

至于这是为什么......我的猜测是因为枚举有点怪异的CLR。例如,值类型枚举基本类型都是自己引用类型,而不是值类型。有一大堆的魔法在幕后事情,如果你从魔术基类强制使用关键字和prevent推导,那么你保持你的意图独立于魔术。

MSDN defines System.Enum as an abstract class:

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

And also MSDN make such statement about abstract class:

But I simply cannot derive from System.Enum. According to Jeffery Richter in his book "CLR via C#", it is C# compiler that forbid that derivation.

And I checked System.Enum's members, most of them are static, which is reasonable for it cannot be instantiated and static methods don't need an object instance to invoke. But there are also some instance methods, such a GetHashCode() and GetTypeCode().

public enum Days:byte { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
Days d = Days.Friday;
d.GetTypeCode();
d.GetHashCode();
解决方案

You can derive from Enum, e.g.

public enum MyEnum
{
    // ...
}

Will be compiled down to something like:

.class public auto ansi sealed MyEnum
    extends System.Enum
{
    // ...
}

The restriction the C# compiler places is that it won't let you write the derivation manually, but instead requires you to use the enum keyword when declaring the type.

As to why this is... my guess is because enumerations are a bit weird in the CLR. For example, the ValueType and Enum base types are both themselves reference types, not value types. There's a whole bunch of magic going on under the covers, and if you force the use of a keyword and prevent derivation from the magic base class, then you are keeping your intent separate from the magic.

这篇关于为什么我不能从System.Enum抽象类派生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:15