反射总结
网络不好直接上代码:
反射获取程序集、类、方法等的总结
protected void Page_Load(object sender, EventArgs e)
{
#region 加载程序集
//1.加载当前目录下面
Assembly ass = Assembly.Load("fanshe");
//2.加载相对路径
Assembly ass1 = Assembly.LoadFile(@"F:\net\code\2017复习\反射\bin\fanshe.dll");
//3.获取当前对象所在的程序集
Assembly ass2 = this.GetType().Assembly;
//4.得到所以当前程序域中的程序集
Assembly[] ass3 = AppDomain.CurrentDomain.GetAssemblies();
#endregion
#region 获取type
/*
获取type
*/
//1.通过程序集获取
Type type1 = ass.GetType("fanshe.Option");
//2.通过typeof获取
Type type2 = typeof(Load);
//3.通过当前对象
Type type3 = this.GetType();
#endregion
#region 获取类
/*
得到对象
*/
//1.通过程序集
object obj = ass.CreateInstance("fanshe.Option");
//2.通过激活器
object obj1 = Activator.CreateInstance(type1);
//如果类中没有无参的构造函数就只能通过下面方式创建
//3.1通过构造器
ConstructorInfo cinfo = type1.GetConstructor(new Type[]
{
typeof(string)
});
object obj4 = cinfo.Invoke(new object[] { "张三" });
//3.2构造器创建无参的
ConstructorInfo cinfo2 = type1.GetConstructor(new Type[] { });
object obj5 = cinfo2.Invoke(new object[] { });
#endregion
#region 获取方法
/*
得到方法
*/
//1.获取程序集
Assembly asse = Assembly.LoadFile(@"F:\net\code\2017复习\反射\bin\fanshe.dll");
//2.获取type
Type t = asse.GetType("fanshe.Option");
//3.获取对象
object obje = asse.CreateInstance("fanshe.Option");
//4.获取方法
MethodInfo minfo = t.GetMethod("Add");
//5.运行方法,传递参数
object add = minfo.Invoke(obje, new object[] { 1, 4 });
Response.Write("和为:" + add);
#endregion
#region 属性
/*
获取属性赋值
*/
//1.获取程序集
Assembly a = Assembly.Load("fanshe");
//2.获取type
Type ty = a.GetType("fanshe.Option");
//3.得到属性
PropertyInfo p = ty.GetProperty("Sum");
//4.得到对象
object o = Activator.CreateInstance(ty);
//5.设置值
p.SetValue(o, 30);
//6.取值
object sum = p.GetValue(o);
Response.Write(sum);
#endregion
}
反射类的代码
namespace fanshe
{
public class Option
{
public Option()
{
}
public Option(string name)
{
this.str1 = name;
}
public string str1;
public int Sum { get; set; }
public int Add(int a,int b )
{
return a + b;
}
public int Long(string str)
{
return str.Length;
}
}
}

浙公网安备 33010602011771号