vendredi 26 décembre 2014

this is a tricky one for me...

First I'll try to explain my scenario, after that it will become the question, be patience... :-)

I'm developing a kind of compiler, so I have a common interface:



interface Command
{
bool IsValid { get; }
// ... another properties
}


And a base class:



class CommandBase<T>: Command where T : CommandBase<T>, new()
{
public bool IsValid { get; set; }
// ... another properties

public static Command Create<T>()
{
return new T();
}
}


With this layout, it becomes easy to create new command, just creating derivated classes like this:



class Command1 : CommandBase<Command1> { }
class Command2 : CommandBase<Command2> { }
... etc


I have a "Interpreter" class where I have an array like this:



CommandsCache = new Func<Command>[]
{
Command1.Create,
Command2.Create
}


Using this array, is easy to find which commands fits better using LINQ:



var command = CommandsCache
.Where(p => /* some checks */)
.FirstOrDefault(p => p.IsValid);


This way I just ripoff a lot of check codes.


Now it comes my question: How can I do to not need to update my array everytime I create a new "command"?


I just come this far:



var commands = typeof(Command)
.Assembly
.GetTypes()
.Where(p => p.IsClass)
.Where(p => p.BaseType != null && p.BaseType.Name.StartsWith("CommandBase"));


Fine, I got all types that IS a "CommandBase" derivated.

But how to invoke the "Create" saying that "T" is one of "commands"?






Aucun commentaire:

Enregistrer un commentaire