C#使用反射機(jī)制實(shí)現(xiàn)延遲綁定
反射允許我們在編譯期或運(yùn)行時獲取程序集的元數(shù)據(jù),通過反射可以做到:
● 創(chuàng)建類型的實(shí)例
● 觸發(fā)方法
● 獲取屬性、字段信息
● 延遲綁定
......
如果在編譯期使用反射,可通過如下2種方式獲取程序集Type類型:
- 1、Type類的靜態(tài)方法
Type type = Type.GetType("somenamespace.someclass");
- 2、通過typeof
Type type = typeof(someclass);
如果在運(yùn)行時使用反射,通過運(yùn)行時的Assembly實(shí)例方法獲取Type類型:
Type type = asm.GetType("somenamespace.someclass");
獲取反射信息
有這樣的一個類:
public class Student { public int Id { get; set; } public string Name { get; set; } public float Score { get; set; } public Student() { this.Id = -1; this.Name = string.Empty; this.Score = 0; } public Student(int id, string name, float score) { this.Id = id; this.Name = name; this.Score = score; } public string DisplayName(string name) { return string.Format("學(xué)生姓名:{0}", name); } public void ShowScore() { Console.WriteLine("學(xué)生分?jǐn)?shù)是:" + this.Score); } }
通過如下獲取反射信息:
static void Main(string[] args) { Type type = Type.GetType("ConsoleApplication1.Student"); //Type type = typeof (Student); Console.WriteLine(type.FullName); Console.WriteLine(type.Namespace); Console.WriteLine(type.Name); //獲取屬性 PropertyInfo[] props = type.GetProperties(); foreach (PropertyInfo prop in props) { Console.WriteLine(prop.Name); } //獲取方法 MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { Console.WriteLine(method.ReturnType.Name); Console.WriteLine(method.Name); } Console.ReadKey(); }
延遲綁定
在通常情況下,為對象實(shí)例賦值是發(fā)生在編譯期,如下:
Student stu = new Student(); stu.Name = "somename";
而"延遲綁定",為對象實(shí)例賦值或調(diào)用其方法是發(fā)生在運(yùn)行時,需要獲取在運(yùn)行時的程序集、Type類型、方法、屬性等。
//獲取運(yùn)行時的程序集 Assembly asm = Assembly.GetExecutingAssembly(); //獲取運(yùn)行時的Type類型 Type type = asm.GetType("ConsoleApplication1.Student"); //獲取運(yùn)行時的對象實(shí)例 object stu = Activator.CreateInstance(type); //獲取運(yùn)行時指定方法 MethodInfo method = type.GetMethod("DisplayName"); object[] parameters = new object[1]; parameters[0] = "Darren"; //觸發(fā)運(yùn)行時的方法 string result = (string)method.Invoke(stu, parameters); Console.WriteLine(result); Console.ReadKey();
到此這篇關(guān)于C#使用反射機(jī)制實(shí)現(xiàn)延遲綁定的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# ListView 點(diǎn)擊表頭對數(shù)據(jù)進(jìn)行排序功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了C# ListView 點(diǎn)擊表頭對數(shù)據(jù)進(jìn)行排序功能的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-04-04C# 定時器?;顧C(jī)制引起的內(nèi)存泄露問題解決
這篇文章主要介紹了C# 定時器保活機(jī)制引起的內(nèi)存泄露問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02基于C#的音樂播放器主Form實(shí)現(xiàn)代碼
這篇文章主要介紹了基于C#的音樂播放器主Form實(shí)現(xiàn)代碼,很實(shí)用的功能,需要的朋友可以參考下2014-08-08C# 撒列實(shí)現(xiàn)關(guān)鍵字過濾的實(shí)例
C# 撒列實(shí)現(xiàn)關(guān)鍵字過濾的實(shí)例,需要的朋友可以參考一下2013-04-04C#控制臺程序?qū)崿F(xiàn)開啟、關(guān)閉SQLServer服務(wù)的代碼分享
這篇文章主要介紹了C#控制臺程序?qū)崿F(xiàn)開啟、關(guān)閉SQLServer服務(wù)的代碼分享,需要的朋友可以參考下2014-05-05