zoukankan      html  css  js  c++  java
  • 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();

    }

     

     

     

     

     

     

     

     

  • 相关阅读:
    AppWidget应用(四)---PendingIntent 之 getService
    AppWidget应用(三)---PendingIntent 之 getBroadcast
    AppWidget应用(二)---PendingIntent 之 getActivity
    JZOJ 3231. 海明距离
    JZOJ 1422. 猴子摘桃
    JZOJ 1421. 二叉树
    SSLOJ 1318.地铁重组
    SSLOJ 1319.埃雷萨拉斯寻宝
    SSLOJ 1317.灵魂分流药剂
    SSLOJ 1316.血色先锋军
  • 原文地址:https://www.cnblogs.com/anyihen/p/5456465.html
Copyright © 2011-2022 走看看