What is a good way to denote \"type\" in database?
I have a base class Action
which is inherited by numerous child classes. Actio
I ended up using option 2, but with less clutter of attributes. Something like this:
public abstract class Action
{
public enum Kind
{
ControlAction = 1,
UpdateAction = 2,
etc
}
public abstract Kind ActionType { get; }
}
public class ControlAction : Action { public override Kind ActionType { get { return Kind.ControlAction; } } }
public class UpdateAction : Action { public override Kind ActionType { get { return Kind.UpdateAction; } } }
The biggest advantage for this is that (even if it meant more typing), it enforces a numeric value to be associated with a class type.
Now class to int is just:
var value = (int)instance.ActionType;
Very fast.
But to convert int to class instance (or class type), I will have to create an instance of each sub action types, and compare its ActionType
property to match the input int value. This is going to be slow. But I can cache somethings and make it faster. Something like:
static readonly Dictionary actionTypes =
GetDefaultInstanceOfAllActions().ToDictionary(x => x.ActionType, x => x.GetType());
public static Action ToAction(this Action.Kind value)
{
return (Action)Activator.CreateInstance(actionTypes[value]);
}
The GetDefaultInstanceOfAllActions
does some reflection (once) to get all types of actions (I use something like this answer for that). I can even make the make the instantiation faster by going the expression route.
The benefits:
Less hassle when creating a new class (no attributes).
Enforces an int to be tied to a class type.
Moderately fast with adequate caching.