C#中的反射(System.Reflection)
一、獲取程序集Assembly
1、獲取當(dāng)前運(yùn)行的程序集
System.Reflection.Assembly[] asm = AppDomain.CurrentDomain.GetAssemblies(); // Assembly b = Assembly.GetExecutingAssembly();
2、獲取指定文件的程序集:Load,LoadFrom,LoadFile方法。
Assembly c = Assembly.Load("mscorlib.dll");//如果你引用了程序及,那么就直接Load()方法,參數(shù)里面程序集名稱就可以加載了。Assembly c = Assembly.Load("mscorlib");
Assembly d = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFrom只能用于加載不同標(biāo)識的程序集, 也就是唯一的程序集, 不能用于加載標(biāo)識相同但路徑不同的程序集。
Assembly e = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFile:只加載指定文件,但不會自動加載依賴程序集二、獲取類型Type (指Class類):
Assembly asm = Assembly.GetExecutingAssembly(); Type[] tArr = asm.GetExportedTypes();//獲取程序集中定義的公共類型
1、從類字符串中獲得Type對象:Assembly.GetType(“”),Module.GetType(“”), Type.GetType(“”)
Assembly ass = Assembly.LoadFrom(@"C:\bin\Debug\ConsoleApplication2.exe");
Console.WriteLine(ass.GetType("ConsoleApplication2.Person").ToString()); //根據(jù)程序集(dll或exe)獲取里面的Class
Module mod = ass.GetModules()[0];
Console.WriteLine(mod.GetType("ConsoleApplication2.Person").ToString());
Type type = Type.GetType("System.Int32");//靜態(tài)方法,參數(shù)為完全限定名(首選)
Type type = Type.GetType("MyAssembly.Example",false,true) //注意0是類名,參數(shù)1表示若找不到對應(yīng)類時是否拋出異常,參數(shù)2表示類名是否區(qū)分大小寫2、從具體類中獲得Type對象:typeof運(yùn)算符
Type t4 = typeof(TestSpace.TestClass);//使用typeof運(yùn)算符
3、從實(shí)例中獲得Type對象:Object.GetType()
Example example = new Example(); Type type = example.GetType(); Type t3 = 42.GetType();//根據(jù)對象實(shí)例獲取類型
4、Type的屬性
t.IsPublic; t.IsAbstract; t.IsClass; t.IsValueType;
三、獲取成員MemberInfo
MemberInfo[] miArr = t.GetMembers(BindingFlags.Instance | BindingFlags.Public);//實(shí)例與公共成員。還有BindingFlags.Static|BindingFlags.NonPublic
foreach (MemberInfo item in miArr)
{
bool a = item is FieldInfo;
PropertyInfo;
MethodBase;
ConstructorInfo;
MethodInfo;
EventInfo;
Type;
}
t.GetConstructor();//獲取構(gòu)造函數(shù)
t.GetFields();//獲取字段
t.GetProperties(); //獲取屬性
t.GetMethods();//獲取方法
t.GetEvents();//獲取事件
t.GetInterfaces();//獲取接口
t.GetCustomAttributes(true);//獲取類型上標(biāo)記的自定義屬性在System.Reflection命名空間內(nèi)包含多個反射常用的類:
- Assembly: 通過此類可以加載操縱一個程序集,并獲取程序集內(nèi)部信息
- EventInfo: 該類保存給定的事件信息
- FieldInfo :該類保存給定的字段信息
- MethodInfo :該類保存給定的方法信息
- MemberInfo :該類是一個基類,它定義了EventInfo、FieldInfo、MethodInfo、PropertyInfo的多個公用行為
- Module :該類可以使你能訪問多個程序集中的給定模塊
- ParameterInfo :該類保存給定的參數(shù)信息
- PropertyInfo: 該類保存給定的屬性信息
四、獲取具體成員
Type t = Assembly.GetExecutingAssembly().GetType("TestSpace.TestClass");
MethodInfo m = t.GetMethod("TestMethod");
ParameterInfo[] p = m.GetParameters();//獲取方法參數(shù)五、創(chuàng)建實(shí)例
1、根據(jù)Assembly創(chuàng)建類型實(shí)例:asm.CreateInstance()
Assembly asm = Assembly.GetExecutingAssembly();
TestClass obj = asm.CreateInstance("TestSpace.TestClass");//根據(jù)Assembly創(chuàng)建類型實(shí)例2、根據(jù)類型創(chuàng)建實(shí)例:Activator.CreateInstance()
Type t = Type.GetType("TestSpace.TestClass");
TestClass obj = (TestClass)Activator.CreateInstance(t);//1、根據(jù)類型創(chuàng)建實(shí)例
TestClass obj = (TestClass)Activator.CreateInstance(t, new object[] { "aa" });// 2、根據(jù)”有參數(shù)的構(gòu)造函數(shù)”創(chuàng)建實(shí)例
//
TestClass obj = (TestClass)t.InvokeMember("TestClass", BindingFlags.CreateInstance, null, null, null);六、調(diào)用方法
1、調(diào)用實(shí)例方法:Invoke
MethodInfo m = t.GetMethod("WriteString");
object returnValue = m.Invoke(obj, new object[] { "test", 1 });//傳兩參數(shù),若方法無參數(shù),可以將Invoke的第二個參數(shù)設(shè)為null
//或者
object returnValue = m.Invoke(obj, BindingFlags.Public, Type.DefaultBinder, new object[] { "test", 1 }, null);//最后一個參數(shù)表示Culture.2、調(diào)用靜態(tài)方法
MethodInfo m = t.GetMethod("StaticMethod");
object returnValue = m.Invoke(null, new object[] { "test", 1 });七、反射屬性
通過System.Reflection.Property能查找到類里面的屬性?!〕S玫姆椒ㄓ蠫etValue(object,object[])獲取屬性值和SetValue(object,object,object[])設(shè)置屬性值
PropertyInfo propertyName = type.GetProperty("Name"); //獲取Name屬性對象
propertyName.SetValue(obj, "張飛", null); //設(shè)置Name屬性的值
object objName = propertyName.GetValue(obj, null); //獲取屬性值根據(jù)屬性的類型設(shè)置屬性的值
Type type = typeof(Person); //注意要輸入全部路徑,包括命名空間
object obj = Activator.CreateInstance(type);
//假設(shè)這是存在于XML的數(shù)據(jù)
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("Id", "1");
dic.Add("Name", "神靈武士");
dic.Add("Birthday", "2001-01-01");
PropertyInfo[] ProArr = type.GetProperties();
foreach (PropertyInfo p in ProArr)
{
if (dic.Keys.Contains(p.Name))
{
p.SetValue(obj, Convert.ChangeType(dic[p.Name], p.PropertyType), null); //當(dāng)需要給屬性設(shè)置不同類型的值時
}
}
Person person = obj as Person;
Console.WriteLine(person.Birthday);八、反射特性
通過System.Reflection.MemberInfo的GetCustomAttributes(Type,bool)就可反射出一個類里面的特性。
Assembly assembly = Assembly.Load("fanshe");
Type type = assembly.GetType("fanshe.Person"); //注意要輸入全部路徑,包括命名空間
object obj = Activator.CreateInstance(type);
object[] typeAttributes = type.GetCustomAttributes(false); //獲取Person類的特性
foreach (object attribute in typeAttributes)
{
Console.WriteLine(attribute.ToString()); //輸出 System.SerializableAttribute 因為我在Person上里加了個[Serializable]
}九、創(chuàng)建委托實(shí)例
TestDelegate myDelegate = (TestDelegate)Delegate.CreateDelegate(typeof(TestDelete), obj, "MyMethod");
string returnValue = myDelegate("Hello");//執(zhí)行委托十、應(yīng)用舉例
1、動態(tài)加載程序集
Assembly asm = Assembly.LoadFrom(@"E:\Test.dll");
Type type = asm.GetType("TestSpace.TestClass");
object obj = System.Activator.CreateInstance(type);//也可以使用強(qiáng)制轉(zhuǎn)換,將obj轉(zhuǎn)換為預(yù)定義的接口或者抽象類(如Form),直接執(zhí)行基方法,不用反射GetMethod .
MethodInfo m = type.GetMethod("WriteString");
m.Invoke(obj, new object[] { "test" });2、獲得List<T>中的T類型:
List<Dog> dogs = new List<Dog>();
Type type = dogs.GetType();
if (type.IsGenericType)
{
Type[] genericArgTypes = type.GetGenericArguments();
if (genericArgTypes[0] == typeof(Dog))
{
//你想要判斷的是這個嗎?
}
}到此這篇關(guān)于C#反射(Reflection)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用正則表達(dá)式實(shí)現(xiàn)首字母轉(zhuǎn)大寫的方法
這篇文章主要介紹了C#使用正則表達(dá)式實(shí)現(xiàn)首字母轉(zhuǎn)大寫的方法,涉及C#基于正則表達(dá)式操作字符串的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
C#向PPT文檔插入圖片以及導(dǎo)出圖片的實(shí)例
PowerPoint演示文稿是我們?nèi)粘9ぷ髦谐S玫霓k公軟件之一,本篇文章介紹了C#向PPT文檔插入圖片以及導(dǎo)出圖片的實(shí)例,非常具有實(shí)用價值,需要的朋友可以參考下。2016-12-12
C#多線程學(xué)習(xí)之(三)生產(chǎn)者和消費(fèi)者用法分析
這篇文章主要介紹了C#多線程學(xué)習(xí)之生產(chǎn)者和消費(fèi)者用法,實(shí)例分析了C#中線程沖突的原理與資源分配的技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-04-04
基于Unity實(shí)現(xiàn)3D版2048游戲的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Unity實(shí)現(xiàn)簡易的3D版2048游戲,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,需要的可以參考一下2023-02-02
unity 文件流讀取圖片與www讀取圖片的區(qū)別介紹
這篇文章主要介紹了unity 文件流讀取圖片與www讀取圖片的對比分析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04

