创建项目
包含两个项目:
控制台项目:ConsoleApplication1
类库项目:ClassLibrary1
代码1:创建一个控制台程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
delegate void DelegateSetter(string value);
static void Main(string[] args)
{
//使用委托,优化反射的速度,为类型A的属性的Set方法加上委托
A r = new A();
//为发射中的对象的属性的set方法加上委托
DelegateSetter ds = (DelegateSetter)Delegate.CreateDelegate(typeof(DelegateSetter), r, typeof(A).GetProperty("name").GetSetMethod());
MethodInfo methodInfo = r.GetType().GetMethod("printB");
object[] param = new object[]{"nihao"};
methodInfo.Invoke(r, param);
ds("hello");
Console.WriteLine(r.name);
//早期反射
Type type = r.GetType();
//加载本地程序集(本项目中)
Assembly assembly = Assembly.Load("ConsoleApplication1");
//获取程序集中的类型
Type ts = assembly.GetType("ConsoleApplication1.A");
//创建实例
//a和obj同样的效果,都是创建实例化A类对象
object a = assembly.CreateInstance("ConsoleApplication1.A");
object obj = Activator.CreateInstance(ts);
//获取类型中的方法
MethodInfo pb = ts.GetMethod("printA");
//执行类型中的方法
pb.Invoke(a, null);
//晚期加载
//程序集
Assembly assembly2 = Assembly.LoadFrom(@"C:\Users\qkf7476\Documents\visual studio 2013\Projects\ConsoleApplication1\"+
@"ClassLibrary1\bin\Debug\ClassLibrary1.dll");
//获取程序集中的类型(包括类)
Type types = assembly2.GetType("ClassLibrary1.Class1");
//创建对象
object c1 = Activator.CreateInstance(types);
//获取类型中的属性
PropertyInfo pi = types.GetProperty("name");
//设置属性值
pi.SetValue(c1, "123");
//获取对象中的属性值
Console.WriteLine(pi.GetValue(c1));
//获取类型中的方法
MethodInfo mi2 = types.GetMethod("PrintName");
//执行类型中的方法
mi2.Invoke(c1, null);
Console.ReadLine();
}
}
public class A
{
public string name { get; set; }
public string address;
public void printA()
{
Console.WriteLine("print A");
}
public void printB(string b)
{
Console.WriteLine(b);
}
}
}
代码2:创建一个类库文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public string name { get; set; }
public string GetName() {
return this.name;
}
public void PrintName() {
Console.WriteLine(this.name);
}
}
}
注意:如果在本项目中使用
Assembly asm3 = Assembly.Load("ClassLibrary1");
那么必须先在本项目中引用ClassLibrary1的项目dll,否则报错。