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、哪里动态了?