C#泛型和反射實(shí)例解析
C#中的泛型和反射經(jīng)常是一起工作的,因此這里就一次性的加以介紹了。
由于c#是強(qiáng)類型語言,一般來說函數(shù)的返回類型和參數(shù)的類型都是一早寫好的,這也就造成了很多時候不像js那樣方便使用,不夠靈話。
因此就有了這個泛型,它可以讓你的函數(shù)和參數(shù)在調(diào)用的時候才決定類型。如下例所示:
public T abc<T>(T word) { return word; return default(T); //關(guān)鍵字default可以對引用類型返回nullAble,int類型返回0,初始化一個T的感覺啦 } abc<string>("x"); //struct 是 值類型 //好處調(diào)用的是如果參數(shù)是值類型可以不用著名 test(100) 而不需要 test<int>(100); public void test<T>(T number) where T : struct { int z = Convert.ToInt32(number); //調(diào)用 test(100); } //下面的不知道好處在哪用在什么地方, public void test2<T>(T lei) where T : class { } public void test3<T>() where T : stooges { } public T test4<T>() where T : new() { T abc = new T(); return abc; } public class stooges { }
加了where 我就不清楚在什么地方用的上了,這個以后再研究
反射能讓我們的代碼運(yùn)行時動態(tài)的獲取一些對象或者類的屬性值等等,甚至是調(diào)用它們。
先來一個常用到的,我們想獲取一個對象的全部屬性和值, 用js 是:
for(var attr in object) { object[attr]=value, attr = attr } var obj = new abc(); Type T = typeof(abc); //typeof(Class) 而不是 typeof(object) 哦 Type V = obj.GetType(); //obj.GetType() 就是typeof(object的class) PropertyInfo[] attrs = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); //獲取attrs foreach (PropertyInfo attr in attrs) { string key = attr.Name; //獲取attr name object value = attr.GetValue(obj, null); //獲取value Type type = attr.PropertyType; //類型 }
關(guān)鍵就是那個 Type , 獲取Type后就可以做很多了
C#常用的方法為:
T.GetProperty("key").GetValue(obj, null); //read a key value T.GetProperty("key").SetValue(obj, "", null); //write a value to key //注意如果是字典 T.GetProperty("Item").GetValue(obj, new [] {"id"}); //先拿Item 然后才通過 new[] {這里放指定的key}
再來看看更詳細(xì)的
class MyClass { public int x { get; set; } public int y { get; set; } public MyClass(int i) { x = y + i; } public MyClass(int i, int j) { x = i; y = j; } public int sum() { return x + y; } }
我們想獲取這個Class 的構(gòu)造函數(shù) :
Type t = typeof(MyClass); ConstructorInfo[] constructors = t.GetConstructors(); //使用這個方法獲取構(gòu)造函數(shù)列表 for (int i = 0; i < constructors.Length; i++) { ConstructorInfo constructor = constructors[i]; //構(gòu)造函數(shù)也是方法所以有 GetParameters ParameterInfo[] parameters = constructor.GetParameters(); //獲取當(dāng)前構(gòu)造函數(shù)的參數(shù)列表 string paraTypeName = parameters[0].ParameterType.Name; //方法的參數(shù)類型名稱 string paraName = parameters[0].Name;// 方法的參數(shù)名 } //調(diào)用構(gòu)造函數(shù) object[] args = new object[2]; args[0] = 10; args[1] = 20; //不用new 直接實(shí)例化 object instance = constructors[0].Invoke(args); //實(shí)例化一個這個構(gòu)造函數(shù)有兩個參數(shù)的類型對象,如果參數(shù)為空,則為null object instance = (t)Activator.CreateInstance(t); 還有這種實(shí)例的方法,不清楚可以放參數(shù)沒有
調(diào)用方法如下:
MethodInfo[] methods = T.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); foreach (MethodInfo method in methods) { string return_name = method.ReturnType.Name; //返回方法的返回類型 string name = method.Name; if (name.Equals("sum", StringComparison.Ordinal)) //指定方法名調(diào)用 { int value = (int)method.Invoke(instance, null); //instance是之前實(shí)例好的對象,方法就是在這個對象之中 } }
下面是一些參考代碼:
Type t = typeof(MyClass); Console.WriteLine("----------------Method------------------"); MethodInfo[] methods = t.GetMethods(); foreach (MethodInfo method in methods) { Console.WriteLine("Method:" + method); //Console.WriteLine(method); //Console.WriteLine("返回值:" + method.ReturnParameter); } Console.WriteLine("---------------Field-------------------"); //字段 ,比如這種 private static string name; FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { Console.WriteLine("Field:" + field); } Console.WriteLine("--------------Member--------------------"); //成員即方法和屬性 MemberInfo[] members = t.GetMembers(); foreach (MemberInfo member in members) { Console.WriteLine("Member:" + member); } Console.WriteLine("--------------Property--------------------"); //屬性 PropertyInfo[] properties = t.GetProperties(); foreach (PropertyInfo property in properties) { Console.WriteLine("Property:" + property); } Console.WriteLine("--------------Constructor--------------------"); //構(gòu)造函數(shù) ConstructorInfo[] constructors = t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance); foreach (ConstructorInfo constructor in constructors) { Console.WriteLine("Constructor:" + constructor); }
調(diào)用不用記太清楚,關(guān)鍵知道什么東西可以用反射獲取和調(diào)用就可以了。
比較常使用的地方是用泛型寫方法的時候,比如我們的泛型是一個不確定的類,然后我們要獲取attr值等等的,就很好可以使用反射了。
還有通過string來調(diào)用方法,這個在js很長用到,比如 obj["methodName"](); 這里也可以用到反射來實(shí)現(xiàn)。
此外還需要注意: 反射的性能是很慢的,也可以說動態(tài)就是慢,這個是很正常的,反射的性能優(yōu)化可以參考使用動態(tài)編程之類的,不過這里就不提了。
相關(guān)文章
C#在復(fù)雜多線程環(huán)境下使用讀寫鎖同步寫入文件
這篇文章介紹了C#在復(fù)雜多線程環(huán)境下使用讀寫鎖同步寫入文件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04C#精確到納秒級別的計(jì)時器類實(shí)現(xiàn)代碼
這篇文章主要介紹了C#精確到納秒級別的計(jì)時器類,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08C# 中屬性PropertyInfo的setvalue用法說明
這篇文章主要介紹了C# 中屬性PropertyInfo的setvalue用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01Unity3d實(shí)現(xiàn)Flappy Bird游戲
這篇文章主要為大家詳細(xì)介紹了Unity3d實(shí)現(xiàn)Flappy Bird游戲,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12