I want to handle the assignment of an enum value in a base class. I'm not sure what Type the backing field should be for the base class, given that the subclass determines from which enum that value will come.
In the base class below I've used object
. I'm looking for the correct base 开发者_开发技巧type instead. I've tried Enum
but while Intellisense doesn't complain about the constructors, I'm having trouble with a lot of other code.
public enum A { One, Two, Three }
public enum B { Four, Five, Six }
public abstract class FooBase
{
object _enumVal;
protected FooBase(object enumVal)
{
_enumVal = enumVal;
}
}
public class Bar : FooBase
{
public Bar(A enumVal):base(enumVal) {}
}
public class Bat : FooBase
{
public Bat(B enumVal):base(enumVal) {}
}
It sounds like you really want generics:
public enum A { One, Two, Three }
public enum B { Four, Five, Six }
public abstract class FooBase<T> where T : struct
{
T _enumVal;
protected FooBase(T enumVal)
{
_enumVal = enumVal;
}
}
public class Bar : FooBase<A>
{
public Bar(A enumVal):base(enumVal) {}
}
public class Bat : FooBase<B>
{
public Bat(B enumVal):base(enumVal) {}
}
You can't specify a generic constraint such that T
has to be an enum within normal C#, but you can do perverse things to the generated code to express that constraint in IL.
精彩评论