简体   繁体   中英

How can I store an efficient table of static class types, and dynamically call methods of these classes in C#?

I'm working on a client-server application which transmits a "command" from one endpoint to another. I want this command to essentialy be an index into a table of class types which can be dynamically created to perform tasks as the commands come in.

I need to store references to a large number of worker classes (~4096 of them) in the most efficient way possible.

Any advice would be greatly appreciated.

Use a dictionary (Key/Value pair or even just an simple array) of an interface type

IMyCommand

and when the command index comes in, just invoke the Execute() method on the interface (or whatever you choose). Of course this requires you instantiate the objects before hand which might not be smart memory wise.

Otherwise, store the fully qualified type name and use reflection to instantiate that type as IMyCommand and then run Execute() method.

You should create a Dictionary<string, ICommand> , or something similar.
For more details, please supply more detail.

If you need to create a new class instance every time, use a Dictionary<string, Func<ICommand>> .

Since you are using static classes, you might want to use a Dictionary<int, Action<T>> or Dictionary<int, Func<T,T>>

On startup populate the dictionary MyDict[0x0001] = StaticClass.StaticMethod"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM