复制代码 代码如下:
using System;
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");
}
}
}
复制代码 代码如下:
using System;
using System.Reflection;
class TestApp
{
public static void Main()
{
Assembly ass;
Type type;
Object obj;
Object any = new Object();
ass = Assembly.LoadFile(@"D:/Source Code/00.C# Sudy/01.Reflection/01/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 };
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);
}
}
新闻热点
疑难解答
图片精选