当前位置:编程学习 > C#/ASP.NET >>

C# 反射小事例

创建一个类库生成dll

namespace TestReflect
{
    public class ReflectTest
    {
        public ReflectTest()
        { 
        }

        public string WriteString(string s)
        {
            return "欢迎您," + s;
        }
        public static string WriteName(string s)
        {
            return "欢迎您光临," + s;
        }

        public string WriteNoPara()
        {
            return "您使用的是无参数方法";
        }
    }
}


继续创建另一个项目引用此dll 


 public void Test()
{
    System.Reflection.Assembly ass;
    Type type;
    object obj;
    try
    {
        //dll路径
        ass = System.Reflection.Assembly.LoadFile(@"D:vs\TestReflect.dll");
        //访问dll中类  命名空间名+类名
        type = ass.GetType("TestReflect.ReflectTest");
        //用来实例化
        obj = ass.CreateInstance("TestReflect.ReflectTest");
        //访问指定实例方法
        System.Reflection.MethodInfo method = type.GetMethod("WriteString");
        string s = (string)method.Invoke(obj, new string[] { "jiangjiang" });
        Response.Write(s + "<br>");
        //访问指定实例方法
        method = type.GetMethod("WriteNoPara");
        s = (string)method.Invoke(obj, null);
        Response.Write(s + "<br>");
        //访问指定静态方法
        method = type.GetMethod("WriteName");
        s = (string)method.Invoke(null,new string[]{"jiang"});
        Response.Write(s + "<br>");

        System.Reflection.MethodInfo[] methods = type.GetMethods();
        //循环输出方法名
        foreach (var item in methods)
        {
            Response.Write(item.Name + "<br>");    
        }
        method = null;
        methods = null;
    }
    catch (Exception ex)
    {

        Response.Write(ex + "<br>");
    }
    finally
    {
        ass = null;
        type = null;
        obj = null;
    }
}
C# 反射 --------------------编程问答-------------------- 学习了 --------------------编程问答-------------------- 忘记在哪里看到了 --------------------编程问答-------------------- 你的问题是什么,还是你只是分享? --------------------编程问答--------------------
引用 3 楼 caozhy 的回复:
你的问题是什么,还是你只是分享?

同问。感觉像是分享。。。 --------------------编程问答-------------------- 帮顶,学习 --------------------编程问答-------------------- 樓主不錯呀,為大牛小牛們解小迷團! --------------------编程问答-------------------- --------------------编程问答-------------------- 都开始做反射了
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,