反射提供了封裝程式集、模組和類型的對象(Type 類型)。可以使用反射動態建立類型的執行個體,將類型綁定到現有對象,或從現有對象擷取類型並調用其方法或訪問其欄位和屬性。如果代碼中使用了屬性,可以利用反射對它們進行訪問。
下面我就以一個案例來說明反射在項目中的使用方法。
大體分為三個步驟:
第一步,在web.config配置如下代碼(目的是為了動態去修改所需分析的dll)
複製代碼 代碼如下:<appSettings>
<add key="BizAssembly" value="PSMS.Biz"/>
</appSettings>
第二步,定義一個用於處理公用程式集的類
複製代碼 代碼如下:/// <summary>
/// 完成從用戶端擷取遠程商務邏輯對象的代理
/// </summary>
public static class FacadeService
{
static IDictionary<string, Type> serviceClassCatalog;//定義一個索引值對介面對象
static FacadeService()
{
serviceClassCatalog = new Dictionary<string, Type>();
Assembly assembly = Assembly.Load(new AssemblyName(ConfigurationManager.AppSettings["BizAssembly"]));//開始載入程式集對象
Type[] types = assembly.GetExportedTypes();//擷取程式集中所有對象的類型集合
Type baseType = typeof(MarshalByRefObject);
foreach (Type type in types)
{
if (baseType.IsAssignableFrom(type))
{
Type[] interfaces = type.GetInterfaces();
//此處登記的是介面類型最終派生的介面類型,即最高層介面
if (interfaces.Length > 0)
{
serviceClassCatalog.Add(interfaces[0].FullName, type);
}
}
}
}
/// <summary>
/// 根據傳入的商務邏輯類的介面類型,返回實現該介面的類型對象執行個體遠程代理
/// </summary>
/// <typeparam name="IFacade">具體的商務邏輯介面類型</typeparam>
/// <returns>實現該介面的類型對象執行個體遠程代理</returns>
public static IFacade GetFacade<IFacade>()
{
string typeName = typeof(IFacade).FullName;
if (serviceClassCatalog.ContainsKey(typeName))
{
object realProxy = Activator.CreateInstance(serviceClassCatalog[typeName]);
return (IFacade)realProxy;
}
else
{
throw new Exception("未包含介面所定義的服務類型。");
}
}
}
第三步,在程式碼中實現調用
複製代碼 代碼如下:public partial class MyTest: System.Web.UI.Page
{
//在後台代碼中構建一個(測試用的)介面的執行個體對象
static IUserInfoFacade userInfoFacade = FacadeService.GetFacade<IUserInfoFacade>();
//其它功能實現代碼
//......
//......
private void Method1()
{
//具體的調用
List<UserInfo> lstUserInfo = userInfoFacade.GetUserInfoList(unitCode, 0, 0);
//其它功能實現代碼
//......
//......
}
}