用C#实现插件函数 [英] PlugIn function implementation with C#

查看:65
本文介绍了用C#实现插件函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 C# 中调用一个函数来调用用户的 dll.

I need to call a function to call user's dll in C#.

例如,当用户创建一个类为 ABC 的 abc.dll 时,我想加载该 dll 以运行类中的方法 xyz(a).

For example, when user makes a abc.dll with class ABC, I want to load the dll to run the methods xyz(a) in the class.

object plugInObject = node.GetPlugInObject("abc.dll", "ABC");
plugInObject.runMethod("xyz", "a");

如何在 C# 中实现这些功能?

How can I implement those functions in C#?

这是插件代码,dll复制为plugin/plugin.dll.

This is plugin code, and the dll is copied as plugin/plugin.dll.

namespace HIR
{
    public class PlugIn
    {
        public int Add(int x, int y)
        {
            return (x + y);
        }
    }
}

这是调用这个插件的那个.

This is the one that calls this plugin.

using System;
using System.Reflection;

class UsePlugIn
{
    public static void Main() 
    {
        Assembly asm = Assembly.LoadFile("./plugin/plugin.dll");
        Type plugInType = asm.GetType("HIR.PlugIn");
        Object plugInObj = Activator.CreateInstance(plugInType);

        var res = plugInType.GetMethod("Add").Invoke(plugInObj, new Object[] { 10, 20 });
        Console.WriteLine(res);
    }
}

推荐答案

它可以在 C# 和 .NET 中翻译成以下内容:

It can be translated in C# and .NET to the following:

Assembly asm = Assembly.LoadFile("ABC.dll");
Type plugInType = asm.GetType("ABC");
Object plugInObj = Activator.CreateInstance(plugInType);

plugInType.GetMethod("xyz").Invoke(plugInObj, new Object[] { "a" });

它被称为反射.

这篇关于用C#实现插件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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