天天看點

反射(5)——動态調用成員

class Person
    {
        public string Name { set; get; }
        public int Age { set; get; }
        public void SayHello()
        {
            Console.WriteLine("你好,我是{0},我的年齡是{1}",Name,Age);
        }

        public void IncAge()
        {
            Age++;
        }

        public void IncAge(int delta)
        {
            Age=Age+delta;
        }
    }

 Type type = typeof(Person);
            object p1 = Activator.CreateInstance(type);
            type.GetProperty("Name").SetValue(p1, "tom", null);
            type.GetProperty("Age").SetValue(p1, 30, null);
            type.GetMethod("SayHello").Invoke(p1, null);
            type.GetMethod("IncAge").Invoke(p1, null);
           

1、使用上面的Person類進行測試。

2、調用Type的GetProperty方法可以根據屬性名獲得屬性對象PropertyInfo,主要成員:CanRead、CanWrite、PropertyType屬性類型;SetValue、GetValue:讀取值,設定值,第一個參數是執行個體對象,因為set、get要針對具體執行個體,最後一個參數null。type.GetProperty(“Age”).SetValue(p1, 30, null),Type、MethodInfo都是和具體對象不相關的,是以需要第一個參數指定要執行的對象。

3、調用Type的GetMethod方法可以根據方法名獲得方法對象MethodBase,調用MethodBase 的Invoke方法就可以調用方法,第一個參數是執行個體對象,第二個參數是參數數組,如果沒有參數設定為null。對Age不能SetValue(p1,"20",null)

4、GetMethod方法預設一個string參數的方法隻能獲得沒有重載方法的方法,要獲得重載方法要用GetMethod(string name, Type[] types)這個重載函數,第二個參數是比對方法的參數類型數組。

5、Type類還有很多方法:GetConstructor(獲得構造函數)、GetEvent(獲得事件)、GetProperties(獲得所有屬性)等。

6、哪裡動态了?