C# 通过反射类动态调用DLL方法

个人觉得"反射"就是能按照规定(微软.net)动态访问特定程序集中对象的工具.

网上找的代码:例子:

//使用反射方:

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\正月龙\Desktop\Person\Person\bin\Debug\Person.dll");
            
//反射出该dll程序集的名称信息.
            Console.WriteLine(a.GetName());
            Console.ReadKey();
            
            
//定义一个"类型信息"的对象.
            Type t = a.GetType("Person.Person"falsetrue);
            
            
//定义一个成员信息类对象数组,并从程序集中获取.
            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, nullnull);

            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();
        }
    }
}
原文地址:https://www.cnblogs.com/webcyz/p/1932410.html