找回密码
 立即注册
楼主: 小米

[脚本] c#反射 示例教程讲解详解

[复制链接]
发表于 2013-5-22 20:04 | 显示全部楼层 |阅读模式
本帖最后由 小米 于 2013-5-22 20:09 编辑

1.新建一个DLL文件
  1. using System;

  2. namespace Webtest
  3. {
  4.   /// <summary>
  5.   /// ReflectTest 的摘要说明。
  6.   /// </summary>
  7.   public class ReflectTest
  8.   {
  9.   public ReflectTest()
  10.   {}

  11.   public string WriteString(string s)
  12.   {
  13.    return "欢迎您," + s;
  14.   }

  15.   /// <summary>
  16.   /// dsajkjflasjdfalksdjfaskfd
  17.   /// </summary>
  18.   /// <param name="s"></param>
  19.   /// <returns></returns>
  20.   public static string WriteName(string s)
  21.   {
  22.    return "欢迎您光临," + s;
  23.   }

  24.   public string WriteNoPara()
  25.   {
  26.    return "您使用的是无参数方法";
  27.   }
  28. }
  29. }
复制代码
2.新建一个asp.net的网页程序 在这里 调用类型 及 方法

public void test1()
   {
    System.Reflection.Assembly ass;
    Type type ;
    object obj;
    try
    {
     ass = System.Reflection.Assembly.LoadFile(@"d:\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[]{"jianglijun"}); //实例方法的调用
   
    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;
   }
  }

评分

参与人数 2鲜花 +1 +1 收起 理由
afteryunlei + 1 赞一个!
cxbsr + 1 很给力!

查看全部评分

发表于 2013-6-3 22:33 | 显示全部楼层

感谢楼主的无私分享!{:soso__11402694654016840197_7:}
发表于 2013-6-8 01:15 | 显示全部楼层
这个反射是什么意思?
发表于 2013-8-8 00:25 | 显示全部楼层
好动地快快保存
发表于 2013-8-13 15:52 | 显示全部楼层
是不是好像缺少些什么!
发表于 2017-3-5 12:47 | 显示全部楼层
楼主是超人
发表于 2017-3-5 12:57 | 显示全部楼层
好帖就是要顶
发表于 2017-3-5 13:02 | 显示全部楼层
真心顶
发表于 2017-3-5 13:43 | 显示全部楼层
难得一见的好帖
发表于 2017-3-5 13:28 | 显示全部楼层
很好哦
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-5 04:56 , Processed in 0.072231 second(s), 23 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表