• C#反射(二)


    长时间没有回顾反射知识了,今天就讲解一下反射的一般第二个用法。

    二.对方法,属性等的反射

     首先需要写一个测试类,生成.exe或.dll文件。

    class Test

        {   public Test()//普通构造方法

            {   }

            public string writeString(string s)//有参方法

            {   return "welcome:" + s;  }

            public static string staticString(string s)//静态方法

            {   return "welcome:" + s;   }

            public string writeStringNO()//无参方法

            {     return "welcome:chen" ;  }}

    找出.exe文件,为了方便寻找,可以暂时复制在桌面上。

    常规调用测试类方法,采用创建一个对象并实例化来引用方法,比如:

      Test t=new Test();

       t.writeString();

    反射调用(两个项目之间调用):

    再创建一个ConsoleApplication2 控制台程序。

    先引用命名空间 using System.Reflection;

    ConsoleApplication2:

    //使用反射

     

    static void Main(string[] args)

    {

    Assembly ass;//程序集

    Type ty;//相当于类

    Object ob;//相当于对象

     

     

    string path = @"C:UsersShuangDesktopConsoleApplication1.exe";//程序集路径

    ass = Assembly.LoadFile(path);//加载程序集

    ty = ass.GetType("ConsoleApplication1.Test");//获取Test类名;格式:"命名空间.类名"

    MethodInfo meth = ty.GetMethod("writeString");//获取方法,格式:"方法名"     有参数

    MethodInfo meth1 = ty.GetMethod("writeStringNO");//获取方法,格式:"方法名"  无参数

    MethodInfo meth2 = ty.GetMethod("staticString");//获取方法,格式:"方法名"   静态

    ob = ass.CreateInstance("ConsoleApplication1.Test");//创建一个对象, 格式:"命名空间.类名"

     

    string[] canshu = { "chen1"};//参数数组

    string res = (string)meth.Invoke(ob,canshu);//获取结果;格式:对象,参数(参数为object数组)    有参数

    string res1 = (string)meth1.Invoke(ob, null);//获取结果;格式:对象,参数(参数为object数组)    无参数

    string res2 = (string)meth2.Invoke(null, canshu);///获取结果;格式:对象,参数(参数为object数组)    静态

    Console.Write("有参:"+res+" ");

    Console.Write("无参:" + res1 + " ");

    Console.Write("静态:" + res2);

     

    Console.ReadLine();

    }

     

     

     

     

     

     

     

     

  • 相关阅读:
    多测师讲解htm_L标题标签001_高级讲师 肖sir
    Shell特殊变量介绍与实践 $0
    shell 变量定义技巧总结
    shell 环境变量的知识小结
    前端 chrome查看html样式基本操作
    shell 命令 env
    date 命令
    shell 命令 set命令
    shell export 命令
    前端 html span标签
  • 原文地址:https://www.cnblogs.com/anyihen/p/5456465.html
Copyright © 2020-2023  润新知