天天看點

c#通過反射動态執行類的執行個體及靜态方法

using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; namespace ConsoleApplication1 {     class Program     {

                 private  static string Display()         {                          return "sex";         }

        private  string Spec()         {

            return "detail";         }         public static void Main(string[] args)         {             //通過反射來執行類的靜态方法             Type tx = typeof(ConsoleApplication1.Program);             MethodInfo mf = tx.GetMethod("Display", BindingFlags.NonPublic|BindingFlags.Static, null, new Type[] { }, null);             string saf = (string)mf.Invoke(null,null);                          Console.WriteLine(saf);

            Console.ReadKey();            

            //通過反射來執行類的執行個體方法             //string[] str = new string[2];             Program p1 = new Program();             Type t = p1.GetType();              //因為此句我分析好久             MethodInfo mi = t.GetMethod("Spec", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);

            //通過反射執行ReturnAutoID方法,傳回AutoID值             string strx = mi.Invoke(p1, null).ToString();             Console.WriteLine(strx);             Console.ReadKey();             }     } }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-720174/,如需轉載,請注明出處,否則将追究法律責任。

轉載于:http://blog.itpub.net/9240380/viewspace-720174/

繼續閱讀