C 反射回顧筆記

2022-07-13 12:09:10 字數 1543 閱讀 7378

反射提供描述程式集、模組和型別的物件(type 型別)。 可以使用反射動態地建立型別的例項,將型別繫結到現有物件,或從現有物件中獲取型別,然後呼叫其方法或訪問其字段和屬性。 如果**中使用了特性,可以利用反射來訪問它們。

反射在以下情況下很有用:

type:表示型別宣告:類型別、介面型別、陣列型別、值型別、列舉型別、型別引數、泛型型別定義,以及開放或封閉構造的泛型型別。

如何獲取type?

1. type t =  typeof(string); string可以是其他型別

2. type t =  string.gettype();

3. type t = type.gettype("system.string"); 及相關過載,注意引數包含命名空間

更多方式參見 

assembly:使用 assembly 來定義和引導程式集,引導程式集清單中列出的模組,以及在此程式集中定位乙個型別並建立乙個它的例項。

如何獲取assembly?

assembly assembly=assembly.load("system");  引數為命名空間

2. loadfile和loadfrom方法為在其中必須由路徑標識程式集的極少數情況下提供。

assembly a = assembly.loadfile(@"d:\c#\reflecttest\reflecttest\dll\utility.dll");  dll或exe全路徑

assembly a = assembly.loadform(@"d:\c#\reflecttest\reflecttest\dll\utility.dll");

3. reflectiononlyload和reflectiononlyloadfrom方法可載入為反射,而不是執行程式集。 與load,loadform類似

public

static

void main(string

args)

}

引數由第二個入參確定,一般多個引數建議使用object傳入(當入參變更時可以減少**修改)

如需獲取私有等方法可以使用過載public methodinfo getmethod(string name, bindingflags bindingattr);等借助bindingflags物件實現。

}應用:利用反射將datatable填充至泛型物件

///

///datatable利用泛型填充實體類

/// ///

實體類 ///

dt ///

public

static ilistdatatabletolist(datatable table)

}list.add(t);

}return

list;

}

java反射回顧《三》

method method demo.getmethod say string.class method.invoke demo.newinstance 名字 執行結果 hello 名字,my name is null nullmethod method demo.getmethod get age...

Day52 反射回顧

反射操作構造器 1 class clazz class.forname com.reflex.bean.user 2 constructor c1 clazz.getconstructor 3 object obj1 c1.newinstance 4 system.out.println obj1 ...

C 基礎知識回顧 反射(1)

反射 reflection 是一種允許使用者獲得型別資訊的c 特性。術語 反射 源自於它的工作方式 type物件對映它所代表的底層物件。對type物件進行查詢可以獲得 反射 與型別相關的資訊。反 射是一種 功能強大的機制,它允許學習和使用只在執行時才能知道的型別功能。這些是官方定義,其實說白了,反射...