Abstract enum in c#

南笙酒味 提交于 2020-01-01 15:07:40

问题


Is there a way to make a (protected) enum abstract in C#?
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".
Is there a working way to achive the desired behaviour?


回答1:


  1. All enums must derive from System.Enum
  2. All enums are value types and hence sealed.

Because of above these two rules, you cannot inherit enums.




回答2:


enum is a keyword, not a class name:

  // 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;
    }
  }



回答3:


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.

This can be achieved by using a generic class and have your enum passed as the templated type. 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)
    {
         .
         .
         .
    }
}



回答4:


No. An enum is an enum, not a class. Only a class can be abstract because only a class can be inherited. 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?



来源:https://stackoverflow.com/questions/26354067/abstract-enum-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!