.net Reflection(反射)- 二

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   tar   

反射 Reflection 中存取方法 

建立一個ClassLibrary類庫:

    public class Student    {        public string Name        { get; set; }        public string School        { get; set; }        public int Sum(int a, int b)        {            return a + b;        }        public string GetName()        {            return "this is book" ;        }       }

 

    /// <summary>    /// 反射    /// </summary>    class Program    {        static void Main(string[] args)        {                        Assembly assembly = Assembly.Load("ClassLibrary");//調用 程式集 類的方法            //建立該對象的執行個體,object類型,參數(名稱空間+類)               object instances = assembly.CreateInstance("ClassLibrary.Student");            //無參數 返回            object value = type.GetMethod("GetName").Invoke(instances, null);       //返回this is book            //有參            object[] params_obj = new object[2];            params_obj[0] = 12;             params_obj[1] = 23;            object value1 = type.GetMethod("Sum").Invoke(instances, params_obj);
   //返回a b和 }

還可以通過 FindInterfaces 方法返回 介面資訊 

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 //擷取程式集介面 Stu 繼承的所有介面           Type t = typeof(Stu);           Type[] interfaces = t.FindInterfaces(TypeFilter, assembly);             //顯示每個介面資訊           foreach (Type i in interfaces)           {               //擷取映射介面方法的類型的方法               InterfaceMapping mapping = t.GetInterfaceMap(i);                 for (int j = 0; j < mapping.InterfaceMethods.Length; j++)               {                   Console.WriteLine(" {0} 實現的 {1}", mapping.InterfaceMethods[j], mapping.TargetMethods[j]);               }           }            

  

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.