使用字符串引用 DLL 类

本文关键字:DLL 引用 字符串 | 更新日期: 2023-09-27 18:36:30

这可能吗?

我一直在制作一个DLL,其中有一个名为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());

我知道上面的代码片段永远不会起作用,但我相信它会最好地反映我的想法。

使用字符串引用 DLL 类

您可以使用反射。

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);

-UPDATE-

首先,我要感谢所有回答我问题的人。我接受了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);

完成此操作后,我开始对如何获取和设置属性,字段和运行方法挠头。我环顾四周了一会儿,发现按照Viru的建议再次使用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 });

我希望这对某人有所帮助!!再次感谢所有发帖的人!

使用字典或其他集合来保留对动态创建对象的引用,如下所示。如果你想要的是真正的动态代码,你将不得不利用Roslyn,或者使用一些脚本沙箱。

var dictClients = new Dictionary<string, ModbusClient>();
dictClients.Add("SomeKey", new ModbusClient(new ModbusRTU()));
var someClient = dictClients["SomeKey"];