我怎么能传递插件通过Assembly.CreateInstance加载参数传递给一个C#? [英] How can I pass an argument to a C# plug-in being loaded through Assembly.CreateInstance?

查看:2902
本文介绍了我怎么能传递插件通过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和另一个主机。既要在同一目录下的code的工作被发现。)

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.)

不过,如果你想创建一个真正可插拔的接口,我建议你使用的初始化方法把给定的参数在你的界面,而不是依赖于构造函数。这样,你可以只是要求插件类实现,而不是希望它接受构造函数中的参数接受你的界面。

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天全站免登陆