I have a abstract base class that I have many inherited classes coming off of. What I would like to do is a static member takes in a string, the first class that can parse the string (only one of the inherited classes should be able to) and return a instance of the inherited class.
This is what i am currently doing.
public static Epl2Command GenerateCommandFromText(string command)
{
lock (GenerateCommandFromTextSyncRoot)
{
if (!Init)
{
Assembly a = Assembly.GetAssembly(typeof(Epl2Command));
Types = new List<Type>(a.GetTypes());
Types = Types.FindAll(b => b.IsSubclassOf(typeof(Epl2Command)));
Init = true;
}
}
Epl2Command ret = null;
foreach (Type t in Types)
{
MethodInfo method = t.GetMethod("GenerateCommand", BindingFlags.Static | BindingFlags.Public);
if (method != null)
ret = (Epl2Command)method.Invoke(null, new object[] { command });
if (ret != null)
break;
}
return ret;
}
I would like it so my code would check all inherited classes without having future programmers come back and edit this function when they add more inherited classes.
Is there a way I can force a inherited class to implement their own GenerateCommand(string)
?
public static abstract Epl2Command GenerateCommand(string command)
is not valid c#. Or am I hammering a nail in with a shoe when I should be using a hammer; any better way of doing this class factory would be appreciated.