接口/基类C#枚举? [英] C# enum in interface/base class?
问题描述
我有枚举问题
我需要做的基类或接口(但空单)一个枚举
I need make a enum in base class or interface (but empty one)
class Base
{
public enum Test;
// ???
}
和后做出不同势枚举
class Parent1
{
public enum Test {A, B, C};
}
class Parent2
{
public enum Test {J, H, K};
}
现在我有方法下一堂课时,我不得不使用枚举
and now i have next class with method when i have to use enum
class Test<T>
{
public void Foo(Test enum)
{
int value = (int) enum;
// ...
}
}
它的存在没有办法做这样的事情?
It's there any way to do something like that ?
如果没有我在每一个类...
If not i have to use static ints in every class ...
class Parent1
{
public static int A = 0;
public static int B = 5;
public static int C = 7;
}
class Parent2
{
public static int J = 1;
public static int H = 3;
public static int K = 6;
}
class Test<T>
{
public void Foo(int enum)
{
int value = enum;
// ...
}
}
我ŧ很糟糕的代码......在一些班级我必须使用20〜+变量
I't looks bad in code ... in some classes i have to use ~20+ variables
推荐答案
有没有这样的事情一个抽象的枚举(即可以在子类中不同的实现) - 但泛型可能是一种选择:
There is no such thing as an abstract enum (that can have different implementations in subclasses) - but generics may be an option:
class Base<T> where T : struct {
private T value;
public void Foo(T value) {
this.value = value;
}
}
class Parent1 : Base<Parent1.Enum1> {
public enum Enum1 {A, B, C};
}
class Parent2 : Base<Parent2.Enum2> {
public enum Enum2 { J, H, K };
}
唯一的问题是,这并不强制执行,只有枚举是可用的 - 你可以在运行时做到这一点,虽然 - 在类型初始化例如:
The only problem is that this doesn't enforce that only enums are usable - you can do this at runtime, though - for example in a type initializer:
static Base() {
if (!typeof(T).IsEnum) throw new InvalidOperationException(
typeof(T).Name + " is not an enum");
}
这篇关于接口/基类C#枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!