C#中反射⾥的invoke⽅法的参数
对于外部调⽤的动态库应⽤反射时要⽤到Assembly.LoadFile(),然后才是获取类型、执⾏⽅法等;
当⽤反射创建当前程序集中对象实例或执⾏某个类下静态⽅法时只需通过Type.GetType("类的完整名")。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
//⼀个最简单的C#反射实例,⾸先编写类库如下:
namespace ReflectionTest
{
public class WriteTest
{
//带参数的公共⽅法
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}
//带⼀个参数的静态⽅法
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}writelines和writeline
//不带参数的静态⽅法
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
public class TestApp
{
public static void Main()
{
Assembly ass;
Type type;
Object obj;
//⽤来测试静态⽅法
Object any = new Object();
//指定类库⽂件必须使⽤绝对路径,不能使⽤相对路径
ass = Assembly.LoadFile(@"c:\ReflectTest.dll");
//命名空间和类的名字必须⼀起指定
type = ass.GetType("ReflectionTest.WriteTest");
/**//*example1---------*/
MethodInfo method = type.GetMethod("WriteString");
string test = "test";
int i = 1;
Object[] parametors = new Object[] { test, i };
//在例⼦1种必须实例化反射要反射的类,因为要使⽤的⽅法并不是静态⽅法。
//创建对象实例
obj = ass.CreateInstance("ReflectionTest.WriteTest"); //执⾏带参数的公共⽅法
method.Invoke(obj, parametors);
//method.Invoke(any, parametors);//异常:必须实例化反射要反射的类,因为要使⽤的⽅法并不是静态⽅法。
/**//*example2----------*/
method = type.GetMethod("StaticWriteString");
method.Invoke(null, new string[] { "test" }); //第⼀个参数忽略//对于第⼀个参数是⽆视的,也就是我们写什么都不会被调⽤,
//即使我们随便new了⼀个any这样的Object,当然这种写法是不推荐的。
//但是对应在例⼦1种我们如果Invoke的时候⽤了类型不⼀致的实例来做为参数的话,将会导致⼀个运⾏时的错误。 method.Invoke(obj, new string[] { "test" });
method.Invoke(any, new string[] { "test" });
method.Invoke(any, new string[] { "test" });
/**//*example3-----------*/
method = type.GetMethod("NoneParaWriteString"); //调⽤⽆参数静态⽅法的例⼦,这时候两个参数我们都不需要指定,⽤null就可以了。 method.Invoke(null, null);
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论