I know that you can't use inheritance with enums, so in my base class I want to define that the classes that implement it must return an enum of some type for a property.
Ideally, this would be like:
public abstract BaseEnum MyEnum { get; set; }
Then all the implementers would have 开发者_StackOverflow社区to return some form of enum. But obviously BaseEnum doesn't exist. I can use object, but I'd rather not.
Is there a nice way of doing this?
Edit: I'm asking this because I essentially want to keep the name of the property in the implementing classes the same - I know that I won't be able to work with the enum in the base class, but if I didn't put it in the base, then the implementing classes could decide on their own property names for their enum, which could become unclear over time, as they would drift towards their own implementations.
All Enums inherit from System.Enum.
The closest you can easily come in C# is to make the type generic with a struct constraint:
public abstract class BaseClass<T> where T : struct
{
public abstract T MyEnum { get; set; }
}
then
public class DerivedClass : BaseClass<SomeEnum>
C# won't let you specify a constraint restricting you to enum types, even though the CLI does support it. I have a project called Unconstrained Melody which uses post-build tricks to enforce such a constraint - but I wouldn't suggest you take the same approach unless you're feeling somewhat daring. The struct constraint will at least limit you to value types, which may be good enough.
You should take a look here: Enum “Inheritance”:
See section 8.5.2 of the CLI spec for the full details. Relevant information from the spec * All enums must derive from System.Enum * Because of the above, all enums are value types and hence sealed
精彩评论