主要使用场景:
int i = 0;
Type type = i.GetType();
//Type t = typeof(int);
Console.WriteLine(type);
输出为:System.Int32
//System.Type.GetType(“T类名”)
//typeof(类型);
//实例.GetType();
获取类型
通过反射实例化对象 ,Type类中的API:Activator.CreateInstance(类型);
FieldsInfo:数据成员信息;
MethodInfos:函数成员信息
通过这两个数据类型获取类型中的所有成员变量和成员方法
通过GetField找到目标变量,通过GetValue 和 SetValue 获取或设置数据的值
通过GetMethod获取目标函数,通过Invoke方法调用函数并传参。
class Test1
{public int age;public int sex;public string name;public void test1(){Console.WriteLine ("test1");}public int test2(){Console.WriteLine("test2");return 1;}public int test3(int age, int sex, string name){this.age = age;this.sex = sex;this.name = name;return -1;}}
internal class Program
{static void Main(string[] args){//Type t = System.Type.GetType("Test1");Type t = typeof(Test1);//实例化object instance = Activator.CreateInstance(t);// 使用存放的数据成员信息给他们设值// FieldInfo: 数据成员信息对象//FieldInfo[] fields = t.GetFields();//根据对象实例中的偏移量 找到目标值FieldInfo ageInfo = t.GetField("age");//将age设置为4ageInfo.SetValue(instance, 4);//Console.WriteLine((instance as Test1).age);//调用成员函数// MethodInfos:函数成员信息对象//MethodInfo[] methods = t.GetMethods();MethodInfo test3Info = t.GetMethod("test3");// 创建的object数组会作为参数传入通过Invoke调用的函数Object[] funcParams = new object[3];funcParams[0] = 22;funcParams[1] = 1;funcParams[2] = "gzy";// Invoke用于执行函数Object ret = test3Info.Invoke(instance, funcParams);Console.WriteLine(ret);}
}
输出:-1