4 c# dll assemblies
我一直在阅读这篇文章 - 我觉得我非常接近答案.我只是想从我创建的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
对于以上片段,所有学分都转到SO用户'woohoo' 如何在C#中调用托管DLL文件?
但是,现在,我希望不仅可以引用我的Dll(及其中的方法),而且可以正确调用其中的方法(在这种情况下,我想调用方法'myVoid').
可能有人对我有什么建议吗?
谢谢,
埃文
您引用的问题和答案是使用反射来调用托管DLL中的方法.如果按照您所说的那样,只需引用您的DLL即可.添加引用(通过Visual Studio中的"添加引用"选项),您可以直接调用方法:
ExampleDLL.Program p = new ExampleDLL.Program(); // get an instance of `Program`
p.myVoid(); // call the method `myVoid`
Run Code Online (Sandbox Code Playgroud)
如果你想要反射路线(由给定的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);
Run Code Online (Sandbox Code Playgroud)
现在你有一个实例,Program可以打电话myVoid.
| 归档时间: |
|
| 查看次数: |
26323 次 |
| 最近记录: |