反射dll里的函数

生成dll的程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ReflectionTest
{
    public class WriteTest
    {
        //public method with parametors  
        public void WriteString(string s, int i)
        {
            Console.WriteLine("WriteString:" + s + i.ToString());
        }

        //static method with only one parametor  
        public static void StaticWriteString(string s)
        {
            Console.WriteLine("StaticWriteString:" + s);
        }

        //static method with no parametor  
        public static void NoneParaWriteString()
        {
            Console.WriteLine("NoParaWriteString");
        }
    }
}

反射调用dll函数的程序
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Reflection;


class TestApp
{
    public static void Main()
    {
        Assembly ass;
        Type type;
        Object obj;

        Object any = new Object();
        ass = Assembly.LoadFile(@"F:\1Test\ReflectTest\ReflectTest\bin\Debug\ReflectTest.dll");//dll文件的绝对路径
        type = ass.GetType("ReflectionTest.WriteTest");//命名空间.类名

        /*example1---------*/
        MethodInfo method = type.GetMethod("WriteString");
        string test = "test";
        int i = 1;
        Object[] parametors = new Object[] { test, i };
        obj = ass.CreateInstance("ReflectionTest.WriteTest");
        method.Invoke(obj,//Instance object of the class need to be reflect  
            parametors);
        //method.Invoke(any, parametors);//RuntimeError: class reference is wrong   

        /*example2----------*/
        method = type.GetMethod("StaticWriteString");
        method.Invoke(null, new string[] { "test" });
        method.Invoke(obj, new string[] { "test" });
        method.Invoke(any, new string[] { "test" });

        /*example3-----------*/
        method = type.GetMethod("NoneParaWriteString");
        method.Invoke(null, null);
    }
}

备注
 

 调用时不需要引用dll文件 

http://blog.csdn.net/bdstjk/article/details/7535230
例子1种必须实例化反射要反射的类,因为要使用的方法并不是静态方法
例子2种我们想用的方法是一个静态方法,这时候Invoke的时候,对于第一个参数是无视的
第三个例子是一个调用无参数静态方法的例子,这时候两个参数我们都不需要指定,用null就可以了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值