zoukankan      html  css  js  c++  java
  • C# 通过反射类动态调用DLL方法

    网上看了很多关于反射的思路和方法,发现这个还算不错

    //使用反射方:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //声明一个反射类对象
                Assembly a;
    
                //让这个对象加载某个外部dll程序集信息.
                a = Assembly.LoadFile(@"C:Users正月龙DesktopPersonPersoninDebugPerson.dll");
                //反射出该dll程序集的名称信息.
                Console.WriteLine(a.GetName());
                Console.ReadKey();
                
                //定义一个"类型信息"的对象.
                Type t = a.GetType("Person.Person", false, true);
                
                //定义一个成员信息类对象数组,并从程序集中获取.
                MemberInfo[] info = t.GetMembers();
                
                //逐个返回成员的名字.
                foreach (MemberInfo inf in info)
                {
                    Console.WriteLine(inf.Name);
                }
                Console.ReadKey();
    
                //定义一个成员方法对象,这里是指定方法名称来获取的.
                MethodInfo method = t.GetMethod("show");
                
                //定义一个查询构造函数的对象,获取时需给定签名.
                ConstructorInfo coninfo = t.GetConstructor(new Type[] { typeof(int), typeof(string) });
                
                //这里准备两个参数,封装为一个具有两个对象的数组.
                object[] arg = new object[2] { 10, "dog" };
                
                //调用构造函数并赋值给一个对象.
                object o = coninfo.Invoke(arg);
                
                //调用对象的方法
                method.Invoke(o, null);
                
                //这是第二种调用对象的方法.都可以.
                method.Invoke(o, BindingFlags.Public | BindingFlags.Instance , Type.DefaultBinder, null, null);
    
                Console.ReadKey();
            }
        }
    }

    //被查询或被调用方

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Person
    {
        public class Person
        {
            private int int_a;
            private string str_a;
            
            public Person()
            { 
            
            }
    
            public Person(int a,string b)
            {
                this.int_a = a;
                this.str_a = b;
            }
    
            public void show()
            {
                Console.WriteLine(int_a.ToString()+":"+str_a);
                Console.ReadKey();
            }
        }
    }
  • 相关阅读:
    247. Strobogrammatic Number II 倒过来看也一样的数
    性能测试结果分析
    性能测试文档
    性能测试技术
    性能测试流程
    JMeter(7)插件
    Java同步工具类
    线程池
    死锁
    Lock显示锁
  • 原文地址:https://www.cnblogs.com/bohetang/p/4057175.html
Copyright © 2011-2022 走看看