简体   繁体   English

c#中的抽象枚举

[英]Abstract enum in c#

Is there a way to make a ( protected ) enum abstract in C#? 有没有办法在C#中制作( protectedenum abstract
Example of base class: 基类示例:

protected abstract enum commands{}; //CS0106        
protected abstract void useCommands(commands meh);  

This does not compile, since " abstract is not valid for this item". 这不会编译,因为“ abstract对此项无效”。
Is there a working way to achive the desired behaviour? 是否有一种工作方式来实现所期望的行为?

  1. All enums must derive from System.Enum 所有枚举必须从System.Enum派生
  2. All enums are value types and hence sealed. 所有枚举都是值类型,因此是密封的。

Because of above these two rules, you cannot inherit enums. 由于上述这两个规则,您无法继承枚举。

enum is a keyword , not a class name : enum关键字 ,而不是类名

  // MyCommand is a class name while 'enum' is a keyword
  public enum MyCommand {
    None,
    Something
  }

So your code should be 所以你的代码应该是

  // Enum (but not enum) is a class name: 
  // Enum is an abstract class for any enum (including MyCommand)
  protected abstract Enum commands {
    get;
  }; 

Possible abstract property implementation could be : 可能的抽象属性实现可能是:

  protected override Enum commands {
    get { 
      return MyCommand.None;
    }
  }

If I understand you, you are trying to make an abstract class which is somewhat similar to a State Machine. 如果我理解你,你试图创建一个类似于状态机的抽象类。 You have an enum storing commands which you want your derived classes to define. 您有一个enum存储命令,您希望派生类定义这些命令。

This can be achieved by using a generic class and have your enum passed as the templated type. 这可以通过使用泛型类来实现,并将您的enum作为模板化类型传递。 Here's an example of how to achieve this. 这是一个如何实现这一目标的例子。

public abstract baseClass <commandType>
{
    protected abstract void useCommands (commandType meh);
    .
    .
    .
}

This can be later derived to be used as follows: 这可以在以后导出使用如下:

public enum commands {stop, wait, go};

public class derivedClass : baseClass <commands>
{
    protected override void useCommands (commands meh)
    {
         .
         .
         .
    }
}

No. An enum is an enum , not a class . 不。 enum是一个enum ,而不是一个class Only a class can be abstract because only a class can be inherited. 只有一个class可以是abstract因为只能继承一个class The point of being abstract is to provide a common base that will be inherited by other types. 抽象的关键是提供一个将由其他类型继承的公共基础。 An enum doesn't inherit anything so how could an abstract enum be implemented or extended? enum不会继承任何内容,那么如何实现或扩展abstract enum

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

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