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

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

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

有帮助吗?

解决方案

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

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

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());
            }
        }
    }
}

其他提示

呼叫

public object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes)

代替。 MSDN文档

编辑:如果你要对此进行投票,请深入了解这种方法为什么是错误的,或者不是最好的方式。

Activator.CreateInstance接受一个Type以及你要传递给Types构造函数的任何内容。

http://msdn.microsoft.com/en -us /库/ system.activator.createinstance.aspx

你也不能使用Activator.CreateInstance,它可以表现得更好。请参阅下面的StackOverflow问题。

如何在Activator.CreateInstance中传递ctor args或使用IL?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top