2008-09-25 60 views

回答

12

你不能。如下例所示,請使用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()); 
      } 
     } 
    } 
} 
2

呼叫

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

代替。 MSDN Docs

編輯:如果您打算投票,請提供深入瞭解爲什麼這種方法是錯誤的或不是最好的方法。

+0

你能發表一些代碼嗎? – 2016-02-23 09:26:52

相關問題