码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-11-05 00:38:00      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:反射   c#反射   执行反射dll的方法   执行方法   c#反射示例   activator   

项目结构:

bubuko.com,布布扣

将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();
        }
    }
}

本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1571868

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

标签:反射   c#反射   执行反射dll的方法   执行方法   c#反射示例   activator   

原文地址:http://962410314.blog.51cto.com/7563109/1571868

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!