如何将参数传递给通过 Assembly.CreateInstance 加载的 C# 插件? [英] How can I pass an argument to a C# plug-in being loaded through Assembly.CreateInstance?

查看:33
本文介绍了如何将参数传递给通过 Assembly.CreateInstance 加载的 C# 插件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在拥有的(成功加载插件)是这样的:

What I have now (which successfully loads the plug-in) is this:

Assembly myDLL = Assembly.LoadFrom("my.dll");
IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass;

这仅适用于具有不带参数的构造函数的类.如何将参数传递给构造函数?

This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor?

推荐答案

你不能.而是使用 Activator.CreateInstance,如下例所示(注意客户端命名空间在一个 DLL 中,而主机在另一个 DLL 中.两者必须位于同一目录中,代码才能工作.)

You cannot. Instead use Activator.CreateInstance as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.)

但是,如果您想创建一个真正可插入的接口,我建议您使用 Initialize 方法,该方法在您的接口中接受给定的参数,而不是依赖于构造函数.这样你就可以只要求插件类实现你的接口,而不是希望"它接受构造函数中接受的参数.

However, if you want to create a truly pluggable interface, I suggest you use an Initialize method that take the given parameters in your interface, instead of relying on constructors. That way you can just demand that the plugin class implement your interface, instead of "hoping" that it accepts the accepted parameters in the constructor.

using System;
using Host;

namespace Client
{
    public class MyClass : IMyInterface
    {
        public int _id;
        public string _name;

        public MyClass(int id,
            string name)
        {
            _id = id;
            _name = name;
        }

        public string GetOutput()
        {
            return String.Format("{0} - {1}", _id, _name);
        }
    }
}


namespace Host
{
    public interface IMyInterface
    {
        string GetOutput();
    }
}


using System;
using System.Reflection;

namespace Host
{
    internal class Program
    {
        private static void Main()
        {
            //These two would be read in some configuration
            const string dllName = "Client.dll";
            const string className = "Client.MyClass";

            try
            {
                Assembly pluginAssembly = Assembly.LoadFrom(dllName);
                Type classType = pluginAssembly.GetType(className);

                var plugin = (IMyInterface) Activator.CreateInstance(classType,
                                                                     42, "Adams");

                if (plugin == null)
                    throw new ApplicationException("Plugin not correctly configured");

                Console.WriteLine(plugin.GetOutput());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.ToString());
            }
        }
    }
}

这篇关于如何将参数传递给通过 Assembly.CreateInstance 加载的 C# 插件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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