1.生成库程序集(Dll) ReflectionTestLab.dll
生成的dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReflectionTestLab
{
public enum MoveDir
{
left,
right,
up,
down,
}
public class Test
{
private int i = 1;
public int j = 0;
public string str = "123";
public MoveDir moveDir;
public Test()
{
}
public Test(int i)
{
this.i = i;
}
public Test(int i, MoveDir moveDir)
{
this.i = i;
this.moveDir = moveDir;
Console.WriteLine("调用构造方法 ---------------------- ");
}
public Test(int i, string str) : this(i)
{
this.str = str;
}
public void Speek()
{
System.Console.WriteLine(i.ToString());
}
public void Move()
{
System.Console.WriteLine("调用--Move");
}
public void Draw()
{
System.Console.WriteLine("调用--Draw");
}
public void Clear()
{
System.Console.WriteLine("调用--Clear");
}
}
}
2.使用反射 调用dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Lesson21_reflection
{
class Program
{
static void Main(string[] args)
{
#region Assembly
// 加载一个指定 程序集
Console.WriteLine("---加载程序集 Assembly" + "ReflectionTestLab.dll ------------------");
Assembly assemble = Assembly.LoadFrom(@"../../../ReflectionTestLab/bin/debug/ReflectionTestLab.dll");
// 同一个目录下
// Assembly.Load("ReflectionTestLab.dll");
Console.WriteLine("---获取 Types " + "------------------");
// 获取程序集中所有的 Types
Type[] types = assemble.GetTypes();
for (int i = 0; i < types.Length; i++)
{
Console.WriteLine(types[i]);
}
Console.WriteLine("---获取 Type " + "ReflectionTestLab.Test ------------------");
// 获取单个Type
Type testType = assemble.GetType("ReflectionTestLab.Test");
// 获取Type的 公共成员变量与方法
Console.WriteLine("---获取 memberInfos " + "testType GetMembers ------------------");
MemberInfo[] memberInfos = testType.GetMembers();
for (int i = 0; i < memberInfos.Length; i++)
{
Console.WriteLine(memberInfos[i]);
}
// 使用反射 获取枚举Type
Type typeDir = assemble.GetType("ReflectionTestLab.MoveDir");
FieldInfo dirRight = typeDir.GetField("right");
// 实例化对象
// 用于快速实例化对象的类
object testObj = Activator.CreateInstance(testType, 9, dirRight.GetValue(null));
Console.WriteLine("---获取方法 调用方法 " + "------------------");
// 获取对象的方法
MethodInfo move = testType.GetMethod("Move");
MethodInfo draw = testType.GetMethod("Draw");
MethodInfo clear = testType.GetMethod("Clear");
// 调用对象的方法
clear.Invoke(testObj, null);
move.Invoke(testObj, null);
draw.Invoke(testObj, null);
// 调用对象的 成员变量
Console.WriteLine("---读取成员变量 " + "------------------");
FieldInfo fieldStr = testType.GetField("str");
Console.WriteLine(fieldStr.GetValue(testObj));
#endregion
#region 总结 反射
// 1.在程序运行时,可以通过反射调用其它应用程序集 以及信息
// 2.信息包括 类、函数、变量、创建对象,实例化以及执行。
// 关键类 Type Assembly Activator
#endregion
Console.ReadLine();
}
}
}