泛型和反射

來源:互聯網
上載者:User

標籤:style   blog   color   使用   for   ar   cti   div   

泛型和反射經常是一起工作的,所以就一次介紹吧.

 

c# 是強型別語言,一般上函數的傳回型別和參數的類型都是一早些好的,也就造成了很多時候不像js那樣方便使用,不靈話。

所以呢就有了這個泛型,它可以讓你的函數和參數在調用的時候才決定類型。

    public T abc<T>(T word)    {        return word;        return default(T); //關鍵字default可以對參考型別返回nullAble,int類型返回0,初始化一個T的感覺啦    }    abc<string>("x");    //struct 是 實值型別     //好處調用的是如果參數是實值型別可以不用著名 test(100) 而不需要 test<int>(100);    public void test<T>(T number) where T : struct    {        int z = Convert.ToInt32(number);        //調用 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 我就不清楚在什麼地方用的上了,這個以後再研究

 

反射能讓我們的代碼運行時動態擷取一些對象或者類的屬性值等等,甚至是調用它們。

先來一個常用到的,我們想擷取一個對象的全部屬性和值, 用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; //類型 }

關鍵就是那個 Type , 擷取Type後就可以做很多了

常用的方法

        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}

 

 

再來看看更詳細的

    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 的建構函式 

            Type t = typeof(MyClass);                     ConstructorInfo[] constructors = t.GetConstructors();  //使用這個方法擷取建構函式列表                   for (int i = 0; i < constructors.Length; i++)            {                ConstructorInfo constructor = constructors[i];                //建構函式也是方法所以有 GetParameters                ParameterInfo[] parameters = constructor.GetParameters(); //擷取當前建構函式的參數列表                string paraTypeName = parameters[0].ParameterType.Name; //方法的參數類型名稱                string paraName = parameters[0].Name;// 方法的參數名                             }                      //調用建構函式            object[] args = new object[2];            args[0] = 10;            args[1] = 20;            //不用new 直接執行個體化            object instance = constructors[0].Invoke(args);  //執行個體化一個這個建構函式有兩個參數的類型對象,如果參數為空白,則為null
object instance = (t)Activator.CreateInstance(t); 還有這種執行個體的方法,不清楚可以放參數沒有

 

調用方法

            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)) //指定方法名調用                {                    int value = (int)method.Invoke(instance, null);  //instance是之前執行個體好的對象,方法就是在這個對象之中                }            }

 

下面是一些參考

        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--------------------"); //建構函式        ConstructorInfo[] constructors = t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);        foreach (ConstructorInfo constructor in constructors)        {            Console.WriteLine("Constructor:" + constructor);        }     

 

調用不用記太清楚,主要知道什麼東西可以用反射擷取和調用就可以了。

比較長使用的地方是用泛型寫方法的時候,比如我們的泛型是一個不確定的類,然後我們要擷取attr值等等的,就很好可以使用反射了。 

還有通過string來調用方法,這個在js很長用到,比如 obj["methodName"](); 這裡也可以用到反射來實現。

p.s : 反射的效能是很慢的,也可以說動態就是慢,這個很正常啦,反射的效能最佳化可以參考使用動態編程之類的,不過這裡就不提先啦。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.