反射示例1-----执行反射dll的方法和获取属性的值

发布时间:2020-10-25 11:26:42 作者:1473348968
来源:网络 阅读:3182

项目结构:

反射示例1-----执行反射dll的方法和获取属性的值

将Document类库生成的DLL文件放在ConsoleApplication2\ConsoleApplication2\bin\Debug文件夹下

-------------------------------------------------------------Document.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Document
{
    public class Document
    {
        public string Name = "李四";
        public string GetName(string name)
        {
            return name;
        }
    }
}

 -------------------------------------------------------------Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //获取程序集
            Assembly asb = Assembly.LoadFrom(Directory.GetCurrentDirectory() + "/Document.dll");
            //获取程序集下面的Document类
            Type document = asb.GetType("Document.Document");
            //实例化Document类对象(有参数的话需要传递object参数)
            object docObj = Activator.CreateInstance(document);
            //获取Document类中的方法
            MethodInfo mi = document.GetMethod("GetName");
            //参数
            object[] parameter = new object[] { "张三" };
            Console.WriteLine(mi.Invoke(docObj, parameter).ToString());//输出方法的返回值:张三
            //获取Document类中的属性
            FieldInfo pi = document.GetField("Name");
            Console.WriteLine(pi.GetValue(docObj));//输出方法的属性:李四
            Console.ReadKey();
        }
    }
}

推荐阅读:
  1. java 反射机制获取类名、属性、方法、构造器和反射动态使用
  2. java 反射-反射对象的获取

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

反射 执行反射dll的方法

上一篇:浅谈C语言共用体和与结构体的区别

下一篇:Java并发 CompletableFuture异步编程的实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》