C#使用Assembly调用DLL中的方法

我一直在读这个 – 我觉得我非常接近答案。 我只是想从我创建的dll文件中调用一个方法。

例如:

我的DLL文件:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ExampleDLL { class Program { static void Main(string[] args) { System.Windows.Forms.MessageBox.Show(args[0]); } public void myVoid(string foo) { System.Windows.Forms.MessageBox.Show(foo); } } } 

我的应用程序:

 string filename = @"C:\Test.dll"; Assembly SampleAssembly; SampleAssembly = Assembly.LoadFrom(filename); // Obtain a reference to a method known to exist in assembly. MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("myVoid"); // Obtain a reference to the parameters collection of the MethodInfo instance. 

对于以上片段,所有学分都转到SO用户’woohoo’ 如何在C#中调用托管DLL文件?

但是,现在,我希望能够不仅引用我的Dll(及其中的方法),而是正确调用其中的方法(在这种情况下,我想调用方法’myVoid’)。

可能有人对我有什么建议吗?

谢谢,

埃文

您引用的问题和答案是使用reflection来调用托管DLL中的方法。 如果你正如你所说的那样,只需要引用你的DLL就没有必要这样做。 添加引用(通过Visual Studio中的“添加引用”选项),您可以直接调用方法:

 ExampleDLL.Program p = new ExampleDLL.Program(); // get an instance of `Program` p.myVoid(); // call the method `myVoid` 

如果你想进入reflection路径(由woohoo给出),你仍然需要一个Program类的实例。

 Assembly SampleAssembly = Assembly.LoadFrom(filename); Type myType = SampleAssembly.GetTypes()[0]; MethodInfo Method = myType.GetMethod("myVoid"); object myInstance = Activator.CreateInstance(myType); Method.Invoke(myInstance, null); 

现在你有一个Program实例,可以调用myVoid

 //Assembly1.dll using System; using System.Reflection; namespace TestAssembly { public class Main { public void Run(string parameters) { // Do something... } public void TestNoParameters() { // Do something... } } } //Executing Assembly.exe public class TestReflection { public void Test(string methodName) { Assembly assembly = Assembly.LoadFile("...Assembly1.dll"); Type type = assembly.GetType("TestAssembly.Main"); if (type != null) { MethodInfo methodInfo = type.GetMethod(methodName); if (methodInfo != null) { object result = null; ParameterInfo[] parameters = methodInfo.GetParameters(); object classInstance = Activator.CreateInstance(type, null); if (parameters.Length == 0) { result = methodInfo.Invoke(classInstance, null); } else { object[] parametersArray = new object[] { "Hello" }; result = methodInfo.Invoke(classInstance, parametersArray); } } } } } 

在获得对方法的引用后,只需添加此行代码即可。

  Method.Invoke(classInstance, new object[] {}); 

希望这有帮助。

MethodInfo有一个名为Invoke的方法。 因此,只需使用您创建的对象调用Method.Invoke() ,例如调用System.Activator.CreateInstance()