C#使用反射機(jī)制實(shí)現(xiàn)延遲綁定
反射允許我們在編譯期或運(yùn)行時(shí)獲取程序集的元數(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)行時(shí)使用反射,通過運(yùn)行時(shí)的Assembly實(shí)例方法獲取Type類型:
Type type = asm.GetType("somenamespace.someclass");
獲取反射信息
有這樣的一個(gè)類:
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)行時(shí),需要獲取在運(yùn)行時(shí)的程序集、Type類型、方法、屬性等。
//獲取運(yùn)行時(shí)的程序集
Assembly asm = Assembly.GetExecutingAssembly();
//獲取運(yùn)行時(shí)的Type類型
Type type = asm.GetType("ConsoleApplication1.Student");
//獲取運(yùn)行時(shí)的對象實(shí)例
object stu = Activator.CreateInstance(type);
//獲取運(yùn)行時(shí)指定方法
MethodInfo method = type.GetMethod("DisplayName");
object[] parameters = new object[1];
parameters[0] = "Darren";
//觸發(fā)運(yùn)行時(shí)的方法
string result = (string)method.Invoke(stu, parameters);
Console.WriteLine(result);
Console.ReadKey();到此這篇關(guān)于C#使用反射機(jī)制實(shí)現(xiàn)延遲綁定的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#用Parallel.Invoke方法盡可能并行執(zhí)行提供的每個(gè)線程
本文主要介紹了C#用Parallel.Invoke方法盡可能并行執(zhí)行提供的每個(gè)線程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01
Unity3D實(shí)現(xiàn)相機(jī)跟隨控制
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)相機(jī)跟隨控制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07
C#實(shí)現(xiàn)位圖轉(zhuǎn)換成圖標(biāo)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)位圖轉(zhuǎn)換成圖標(biāo)的方法,可實(shí)現(xiàn)將bmp格式位圖轉(zhuǎn)換成ico格式圖標(biāo)的功能,需要的朋友可以參考下2015-06-06
C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例詳解
這篇文章主要介紹了C#通過PInvoke調(diào)用c++函數(shù)的備忘錄的實(shí)例以及相關(guān)知識點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2019-08-08

