C#中使用大会DLL中调用一个方法 [英] C# Using Assembly to call a method within a DLL

查看:116
本文介绍了C#中使用大会DLL中调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读了很多关于这一点 - 我觉得我非常接近的答案。 。我只是希望调用从我创建了一个DLL文件中的方法

I have been reading a lot about this - I feel like I'm very close to the answer. I am simply looking to call a method from within a dll file that I have created.

例如用途:

结果

For example purposes:

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用户呜呼在上面的代码片段
如何调用托管DLL文件中C#?

All credits go to SO user 'woohoo' for the above snippet How to call a Managed DLL File in C#?

现在,不过,我想能不能只引用我的DLL(和方法里面),但正确调用里面的方法(在这种情况下,我想调用方法'myVoid')

Now, though, I would like to be able to not only reference my Dll (and the methods inside it) but properly call the methods inside it (in this case I would like to call method 'myVoid').

也许任何人有什么建议吗?

Might anyone have any suggestions for me?

感谢您,

埃文

推荐答案

问题和回答您参考使用反射来调用托管DLL的方法。这是没有必要的,如果像你说你想做什么,你只需简单地引用您的DLL。添加引用(通过在Visual Studio中添加引用选项),你可以直接打电话给你的方法,像这样:

The question and answer you reference is using reflection to call the method in the managed DLL. This isn't necessary if, as you say you want to do, you simply reference your DLL. Add the reference (via the Add Reference option in Visual Studio), and you can call your method directly like so:

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

如果你想要去的路线反射(通过<给出code>呜呼),你仍然需要你的程序类的一个实例。

If you want to go the reflection route (as given by woohoo), you still need an instance of your Program class.

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

现在你有程序的一个实例和可以调用 myVoid

这篇关于C#中使用大会DLL中调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆