开发者

Enums and inheritance

I will use (again) the following class hierarchy:

Event

and all the following classes inherit from Event:

SportEventType1 SportEventType2 SportEventType3 SportEventType4

I have originally designed the Event class like this:

public abstract class Event
{
    public abstract EventType EventType { get; }
    public DateTime Time { get; protected 开发者_如何学JAVAset; }

    protected Event(DateTime time) {
        Time = time;
    }
}

with EventType being defined as:

public enum EventType {
    Sport1,
    Sport2,
    Sport3,
    Sport4
}

The original idea would be that each SportEventTypeX class would set its correct EventType. Now that I think of it, I think this approach is totally incorrect for the following reasons:

  1. If I want to later add a new SportEventType class I will have to modify the enum
  2. If I later decide to remove one SportEventType that I feel I won't use I'm also in big trouble with the enum.
  3. I have a class variable in the Event class that makes, afterall, assumptions about the kind of classes that will inherit from it, which kinda defeats the purpose of inheritance.

How would you solve this kind of situation? Define in the Event class an abstract "Description" property, having each child class implement it? Having an Attribute(Annotation in Java!) set its Description variable instead? What would be the pros/cons of having a class variable instead of attribute/annotation in this case? Is there any other more elegant solution out there?

Thanks


I would not do an enum for an EventType, if your subclass is going to be EventTypes. Enums are good for a fixed set of options - in your case, you want the flexibility of inheritance, so just use subclassing directly.

If it's just a matter of description, I would do something like:

public abstract class Event
{
    public string Description { get; private set;}
    public DateTime Time { get; protected set; }

    protected Event(string description, DateTime time) {
        this.Description = description;
        Time = time;
    }
}

This just lets your subclasses specify this for you, and it sounds like that is what you're after anyways.


You could simply use the is operator and forget about an enum.

var myEvent = Event.Create(type);

if (myEvent is BaseballGame)
{
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜