[英]How do you instantiate an object that is not included in your C# project?
注意:所有示例代碼都大大簡化了。
我有一個DLL定義為:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
namespace RIV.Module
{
public interface IModule
{
StringWriter ProcessRequest(HttpContext context);
string Decrypt(string interactive);
string ExecutePlayerAction(object ParamObjectFromFlash);
void LogEvent(object LoggingObjectFromFlash);
}
}
現在,在我的解決方案之外,其他開發人員可以定義具體的類並將它們放入我的應用程序的BIN文件夾中。 也許是這樣的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RIV.Module;
namespace RIV.Module.Greeting
{
public class Module : IModule
{
public System.IO.StringWriter ProcessRequest(System.Web.HttpContext context)
{
//...
}
public string Decrypt(string interactive)
{
//...
}
public string ExecutePlayerAction(object ParamObjectFromFlash)
{
//...
}
public void LogEvent(object LoggingObjectFromFlash)
{
//...
}
}
}
現在,在我的應用程序中,我需要知道一個新的模塊可用(我猜通過web.config或其他類似的東西),然后能夠根據數據庫Campaign表中的一些觸發器調用它(這些映射到用於該特定活動的模塊)。
我試圖以這種方式實例化它:
var type = typeof(RIV.Module.Greeting.Module);
var obj = (RIV.Module.Greeting.Module)Activator.CreateInstance(type);
但是,編譯器打氣,因為從未將引用設置為RIV.Module.Greeting.dll !
我究竟做錯了什么?
你需要使用更多的反射:
Assembly.Load
加載程序集 someAssembly.GetType(name)
或搜索someAssembly.GetTypes()
查找類型 Type
實例傳遞給Activator.CreateInstance
而不是typeof(RIV.Module.Greeting.Module),嘗試使用
var type = Type.GetType("RIV.Module.Greeting.Module, RIV.Module.Greeting");
(即通過將其程序集限定的名稱指定為字符串來加載類型)並轉換為IModule。
這種方法要求您知道模塊的確切類和程序集名稱(如您所寫,它們可以存儲在web.config中)。
或者,您可以采用完全動態的插件方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.