C # Polymorphism - Like Not Types of Hard Code

I am making a simple object-oriented test program to try to help me deal with OOP. I have an ICommand inteface that has a Run method (params object []), and I have various classes that use this interface and implement their own versions of run. Each class also has a name property that says what the command is and what it does.

I want to have a graphical interface where I can create commands that will probably require some kind of list in order to select the type of command to create. The question is, how do I make this list and make it work without hardcoding in the switch statement with explicit references to all the classes that I created.

I'm sure this is a really simple problem that I should know about, but I just can't think about it! I am sure there is an answer though.

Oh, and I expect some of the answers to say to read the book “Design Templates”: well, the only copy in the library is not available at the moment, but I will read it as soon as possible!

Update: I just posted the following question here

+1
source share
4 answers

Save all your classes in the general ICommand list, override ToString () with the name of your command and apply the contents of the list to your list.

var commandlist = new List<ICommand>();
commandList.add(new Command("Run"));
commandList.add(new Command("Walk"));
commandList.add(new Command("Crawl"));
+2
source

( wikipedia), invoke reflection. , .

+1

, . - - :

 var commands = new List<object>();
 foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
 {
    foreach (Type type in assembly.GetTypes())
    {
       if (type.GetInterface(typeof(ICommand).FullName) != null)
       {
          commands.Add(Activator.CreateInstance(type));
       }
    }
 }

, , ICommand, .

(, , ).

. , CommandFactory, .

+1

You can use reflection to find all classes that implement an interface that interests you; then use this to populate your list

0
source

All Articles