您的位置:首页 > 编程语言 > C#

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: