Reflection(反射)[C#]
2009-07-05 00:18
495 查看
反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。[MSDN]
使用:
using System; namespace Webtest { /**/ /// <summary> /// ReflectTest 的摘要说明。 /// </summary> public class ReflectTest { public ReflectTest() { } public string WriteString(string s) { return "欢迎您," + s; } /**/ /// <summary> /// dsajkjflasjdfalksdjfaskfd /// </summary> /// <param name="s"></param> /// <returns></returns> public static string WriteName(string s) { return "欢迎您光临," + s; } public string WriteNoPara() { return "您使用的是无参数方法"; } } }
使用:
public class WebForm1 { protected void Page_Load(object sender, EventArgs e) { } public void test() { System.Reflection.Assembly ass; Type type; object obj; try { ass = System.Reflection.Assembly.Load("TestReflect"); TestReflect为dll的名称 type = ass.GetType("Webtest.ReflectTest");//必须使用名称空间+类名称 System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称 obj = ass.CreateInstance("Webtest.ReflectTest");//必须使用名称空间+类名称 string s = (string)method.Invoke(obj, new string[] { "chenya" }); //实例方法的调用 Response.Write(s + "<br>"); method = type.GetMethod("WriteName");//方法的名称 s = (string)method.Invoke(null, new string[] { "jianglijun" }); //静态方法的调用 Response.Write(s + "<br>"); method = type.GetMethod("WriteNoPara");//无参数的实例方法 s = (string)method.Invoke(obj, null); Response.Write(s + "<br>"); method = null; } catch (Exception ex) { Response.Write(ex + "<br>"); } finally { ass = null; type = null; obj = null; } } }
相关文章推荐
- C#反射Reflection学习随笔
- C# 关于反射类[System.Reflection]的一个小例子
- C#反射(Reflection)对类的属性get或set值
- C# Reflection反射学习
- [整理]C#反射(Reflection)详解
- C# 反射(Reflection)
- C#使用反射(Reflection)实现深复制与浅复制
- C#反射(Reflection)对类的属性get或set值 .
- C#反射Reflection
- C# System.Reflection 反射
- C#反射的使用(Reflection)
- [转]C# 关于反射类[System.Reflection] 根据类名 动态调用 类方法
- 【C#学习】Reflection 反射
- [整理]C#反射(Reflection)详解
- C#之玩转反射【转:http://www.cnblogs.com/yaozhenfa/p/CSharp_Reflection_1.html】
- C#反射(Reflection)
- [整理]C#反射(Reflection)详解
- C# 反射(Reflection)
- C#_Assembly-Reflection_程序集与反射
- C# 反射(Reflection)