程序集定义:【.net平台】应用程序编译后的结果 exe,dll,….
反射:获取程序集中信息的技术叫反射。
反射可以动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法。
反射的作用:
1. 了解类型信息
2.动态创建类型实例【对象】,动态访问实例的成员【调用方法】
动态 优点:灵活!可维护!》复用性好!【缺点 性能略低】
反射使用案例↓
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;//
namespace DemoReflection
{
class Program
{
static void Main1(string[] args)
{
//1得到Type类数据类型的对象!
//Type typeObj = Type.GetType("DemoReflection.Student");
//Type typeObj = (new Student()).GetType();
Type typeObj = typeof(Student);
//2 了解类型信息(查看类型信息,了解本身信息,成员信息)
//或动态创建对象
//或动态调用方法
MemberInfo[] mArr= typeObj.GetMembers();
//MemberInfo[] mArr2 = typeObj.GetMethods();
//var re = typeObj.GetEvents();
}
static void Main(string[] args)
{
//1得到Type类数据类型的对象!
Type typeObj = Type.GetType("DemoReflection.Student");
//2 动态【使用反射技术】创建对象//或动态调用方法
//静态创建对象Student obj = new Student();
object obj=Activator.CreateInstance(typeObj);
Student stuObj = (Student)obj;
//动态【使用反射技术】调用方法
MethodInfo method = typeObj.GetMethod("Test2");
//(对象,参数)
method.Invoke(stuObj, new Object[]{"ok:"});
//调用完毕
Console.ReadKey();
}
}
class Student
{
public string Name = "ok";//使用反射调用Name
public int Id { get; set; }
public void Test()
{
Console.WriteLine("考试~!");
}
public void Test2(string a)
{
Console.WriteLine(a+"考试~!");
}
}
}
反射常用类
取得数据类型Type 对象的方法;
如何得到Type
方式一:Type.GetType(“类型全名”); 重点!
适合于类型的名称已知
方式二:obj.GetType();
适合于类型名未知,类型未知,存在已有对象
方式三:typeof(类型)
适合于已知类型
方式四:Assembly.Load(“XXX”).GetType(“名字”);
适合于类型在另一个程序集中 “D://../prj2.dll”
Type类常用Get系列方法 Is系列属性
System.Reflection 命名空间
MethodInfo(方法)
重要方法: Invoke
PropertyInfo(属性)
重要方法:SetValue GetValue
FieldInfo(字段)
重要方法:SetValue GetValue
ConstructInfo(构造方法)
重要方法:Invoke
动态创建对象
Activator.CreateInstance(string 程序集名称,string 类型全名).Unwarp()
Activator.CreateInstance(Type type);
Assembly assembly = Assembly.Load(程序集);
assembly.CreateInstance(Type);
//找到有参构造方法,动态调用构造方法
type.GetConstructor(typeof(string)).Invoke()