[英]Abstract enum in c#
Is there a way to make a ( protected
) enum
abstract
in C#? 有没有办法在C#中制作(
protected
) enum
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? 是否有一种工作方式来实现所期望的行为?
System.Enum
System.Enum
派生 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.