2012年5月30日 星期三

Method Invoke

//Car Class
namespace Com.Testing {
    class Car {
        public static string GetInfo() {
            return "資訊";
        }

        public string GetInfo(string s1, int i) {
            return s1 + i;
        }

        public string GetInfo(string s1) {
            return s1;
        }

    }
}

//Main
 //絕對路徑
 System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFile(@"D:\MyLibrary.dll");
 //命名空間+Class 名稱
Type type = ass.GetType("Com.Testing.Car");
 //因有overload, 需加上參數型別
 System.Reflection.MethodInfo method = type.GetMethod("GetInfo", new Type[] { typeof(string), typeof(int) });

 //實列方法
 object obj = ass.CreateInstance("Com.Testing.Car");
 string result = (string)method.Invoke(obj, new object[] { "測試", 1 });
 Console.WriteLine(result);
 //靜態方法
 method = type.GetMethod("GetInfo", new Type[] {});
 result = (string)method.Invoke(null, new object[] {});
 Console.WriteLine(result);