[英]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. 我需要以尽可能最有效的方式存储对大量工作者类(其中约4096个)的引用。
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). 当命令索引进入时,只需在接口(或您选择的任何接口)上调用Execute()方法。 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. 否则,存储完全限定的类型名称,并使用反射将其实例化为IMyCommand,然后运行Execute()方法。
You should create a Dictionary<string, ICommand>
, or something similar. 您应该创建一个
Dictionary<string, ICommand>
或类似的东西。
For more details, please supply more detail. 有关更多详细信息,请提供更多详细信息。
If you need to create a new class instance every time, use a Dictionary<string, Func<ICommand>>
. 如果您每次需要创建一个新的类实例,请使用
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>>
由于您使用的是静态类,因此可能要使用
Dictionary<int, Action<T>>
或Dictionary<int, Func<T,T>>
On startup populate the dictionary MyDict[0x0001] = StaticClass.StaticMethod"
启动时,填充字典
MyDict[0x0001] = StaticClass.StaticMethod"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.