C#反射在實際應用中的執行個體代碼

來源:互聯網
上載者:User

反射提供了封裝程式集、模組和類型的對象(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);
//其它功能實現代碼
//......
//......
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.