这个是可能的吗?
我已经创建了一个动态链接库,里面有一个名为ModbusClient的类和一个名为ModbusRTU的类。在另一个应用程序中,我添加了以下代码。
ModbusClient Client = new ModbusClient(new ModbusRTU());
它可以工作,但现在我要做的是从三个字符串中动态添加客户端!如以下代码所示。
string string1 = "Modbus";
string string2 = "Client";
string string3 = "RTU";
string1+string2 Client = new string1+string2(new string1 + string3());
我知道上面的代码片段永远不会工作,但我相信它最能反映我的想法。
发布于 2016-02-28 13:55:37
你可以使用反射..
string string1 = "Modbus";
string string2 = "Client";
string string3 = "RTU";
var modbusClientType = Type.GetType(string1+string2);
var modbusRtuType = Type.GetType(string1+ string3);
var modbusRtuInstance = Ativator.CreateInstance(modbusRtuType);
var modbusClientInstance = Activator.CreateInstance(modbusClientType,modbusRtuInstance);
发布于 2016-03-03 19:45:36
更新--
首先,我要感谢所有回答我问题的人。我采纳了Viru的建议,使用了"GetType“方法。一开始它不起作用,但我可以稍微调整一下,以获得想要的效果。这就是它现在的样子,并且对我所需要的很好。顺便说一句,DataExchange.Modbus是我在原始帖子中引用的DLL的名称。
string string1 = "Modbus";
string string2 = "Client";
string string3 = "RTU";
var modbusClientType = Type.GetType("DataExchange.Modbus." + string1 + string2 + ",DataExchange.Modbus");
var modbusRtuType = Type.GetType("DataExchange.Modbus." + string1 + string3 + ",DataExchange.Modbus");
var modbusRtuInstance = Activator.CreateInstance(modbusRtuType);
var Client = Activator.CreateInstance(modbusClientType, modbusRtuInstance);
做完这些之后,我开始对如何获取和设置属性、字段和run方法感到困惑。我看了看周围一段时间,发现可以像病毒建议的那样再次使用System.Reflection。
//Type
var t = Client.GetType();
//Properties "Changes the name property of Client"
PropertyInfo Client_Name = t.GetProperty("Name");
Client_Name.SetValue(Client, "NEW NAME");
//Registers "Gets an array from the Client"
FieldInfo Registers = t.GetField("Registers");
Array arr = (Array)Registers.GetValue(Client);
Label_Register1.Text = String.Format("0x{0:x4}", arr.GetValue(246));
Label_Register2.Text = String.Format("0x{0:x4}", arr.GetValue(247));
//Mothods "Executes a method with parameters {_portClient to , 1 }"
MethodInfo method = t.GetMethod("Execute");
method.Invoke(Client, new object[] { _portClient, Convert.ToByte(1), Convert.ToByte(4), 247, 2, 1 });
我希望这能帮助一些人!!再次感谢所有发帖的人!
发布于 2016-02-28 15:03:58
使用字典或其他集合来保留动态创建的对象的引用,如下所示。如果你想要的是真正的动态代码,你将不得不利用Roslyn,或者使用一些脚本沙箱。
var dictClients = new Dictionary<string, ModbusClient>();
dictClients.Add("SomeKey", new ModbusClient(new ModbusRTU()));
var someClient = dictClients["SomeKey"];
https://stackoverflow.com/questions/35679188
复制相似问题