本文實例講述了asp.net反射簡單應(yīng)用。分享給大家供大家參考,具體如下:
反射提供了封裝程序集、模塊和類型的對象(Type 類型)。可以使用反射動態(tài)創(chuàng)建類型的實例,將類型綁定到現(xiàn)有對象,或從現(xiàn)有對象獲取類型并調(diào)用其方法或訪問其字段和屬性。如果代碼中使用了屬性,可以利用反射對它們進(jìn)行訪問。----這是反射最簡單的理解。下面就是一個最簡單的實例來講述反射技術(shù)的應(yīng)用!
一. 聲明接口,接口中包含一個虛方法。如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public interface IReflect { void Run(string name); } }
二. 實現(xiàn)接口,實現(xiàn)接口中的方法。如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { public class Reflect:IReflect { public void Run(string name) { Console.WriteLine(name+"開始跑了!"); } } }
三. 通過反射技術(shù)來創(chuàng)建類型的實例,并調(diào)用實例的方法。如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IReflect rec = (IReflect)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1.Reflect"); rec.Run("aaa"); Console.ReadLine(); } } }
這樣一個簡單的實例就完成了,顯示的結(jié)果就是“aaa開始跑了”。反射的命名控件是System.Reflection,在使用時候一定要引用該命名控件,該命名控件長用的對象就是Assembly,該對象包含許多靜態(tài)方法。其中Load就是很典型的。CreateInstance是用來創(chuàng)建某個對象的實例。
更多關(guān)于asp.net相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《asp.net優(yōu)化技巧總結(jié)》、《asp.net字符串操作技巧匯總》、《asp.net操作XML技巧總結(jié)》、《asp.net文件操作技巧匯總》、《asp.net ajax技巧總結(jié)專題》及《asp.net緩存操作技巧總結(jié)》。
希望本文所述對大家asp.net程序設(shè)計有所幫助。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com