主要使用场景:
主要用途
反射用到的命名空间
System.Reflection;
System.Type;
System.Reflection.Assembly;
反射用到的主要类
//访问被反射数据类型的元数据
System.Type;
//用于访问给定程序集信息,或者将程序集加载到程序中。
System.Reflection.Assembly
//使用typeof运算符
Type t1 = typeof(string);
//使用对象.GetType()方法
string s = "gzy";
Type t2 = s.GetType();
//使用Type类的静态方法GetType(string typeName);
Type t3 = Type.GetType("System.String");
Name 数据类型名
FullName 数据类型完全限定名(包括命名空间名)
Namespace 命名空间名
IsAbstract 是否是抽象类型
IsArray 是否是数组
IsClass 是否是类
IsEnum 是否是枚举
IsInterface 是否是接口
IsPublic 是否共有
IsSealed 是否是密封类(不可继承)
IsValueType 是否是值类型
GetConstructor(), GetConstructors(); //返回构造函数 ConstructorInfo
GetEvent(), GetEvents(); //返回事件信息 EventInfo
GetField(), GetFields(); //返回成员变量信息 FieldInfo
GetInterface(), GetInterfaces(); //返回接口信息 InterfaceInfo
GetMember(), GetMembers(); //返回所有成员信息 MemberInfo
GetMethod(), GetMethods(); //返回所有方法信息 MethodInfo
GetProperty(), GetProperties(); //返回属性信息 PropertyInfo
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:数据成员信息;
MethodInfo:函数成员信息
通过这两个数据类型接收 获取到对象中的所有成员变量和成员方法
通过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设置为4
ageInfo.SetValue(instance, 4);
//Console.WriteLine((instance as Test1).age);
//调用成员函数
// MethodInfo:函数成员信息对象
MethodInfo test3Info = t.GetMethod("test3");
// MethodInfo[] methods = t.GetMethods();
// 创建的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