反射用法。
namespace aaaaa {
public class User
{
//字段
public string Field;
//属性
public string Name { get; set; }
//构造函数
public User()
{
this.Name = "无参构造";
}
public User(string name)
{
this.Name = name;
}
//public函数
public void PublicShow()
{
Console.WriteLine(string.Format("反射调用一个public方法"));
}
//private函数
private void PrivateShow()
{
Console.WriteLine(string.Format("反射调用一个Private方法"));
}
//static函数
public static string StaticMethod()
{
return "反射调用了一个Static方法";
}
//带参带返回值函数
public string GetString(string name)
{
return string.Format("大家好,我的名字是:{0}!", name);
}
//事件
public event EventHandler eventHandler;
//事件处理函数
public void DoEvent()
{
if(eventHandler != null)
eventHandler(null, EventArgs.Empty);
}
}
}
把上面编译好的库 aaaa.dll 复制到Debug目录下
//获取程序集
Assembly assembly = Assembly.Load("aaaaa");
Assembly assembly2 = Assembly.LoadFrom("aaaaa.dll");
//从程序集中获取指定对象类型;
Type type = assembly.GetType("aaaaa.User");
//使用Activator创建实例(无参数构造函数)
var user1 = Activator.CreateInstance(type);
//使用Activator创建实例(带参数构造函数)
var user2 = Activator.CreateInstance(type, "ss");
//使用Assembly创建实例(无参数构造函数)
var user3 = assembly.CreateInstance("aaaaa.User");
//反射无参构造函数
ConstructorInfo constructor1 = type.GetConstructor(new Type[] {});
var user4 = constructor1.Invoke(new object[] { });
//反射有参构造函数
ConstructorInfo constructor2 = type.GetConstructor(new Type[] { typeof(string) });
var user5 = constructor2.Invoke(new object[] { "ss" });
//调用public函数(无参数)
type.InvokeMember("PublicShow",
BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, user1,
null);
//调用public函数(带参数)
string returnValue =
type.InvokeMember("GetString",
BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding, null, user1,
new object[] { "ss" }) as string;
// 调用静态方法
string returnValue2 =
type.InvokeMember("StaticMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
null, null, new object[] {}) as string;
// 调用私有方法 .
type.InvokeMember("PrivateShow",
BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, user1,
new object[] {});
//反射属性
var Name =
type.InvokeMember("Name", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance, null,
user1, new object[] {}) as string;
//设置属性(设置Name属性为"新属性")
type.InvokeMember("Name", BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance, null,
user1, new object[] {"新属性"});
//反射字段
string Field =
type.InvokeMember("Field", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance, null,
user1, new object[] {}) as string;
//设置字段(设置Field字段为"新字段")
type.InvokeMember("Field", BindingFlags.SetField | BindingFlags.Public | BindingFlags.Instance, null,
user1, new object[] { "新字段" });