使用C#进行Reflection编程
2024-07-21 02:19:35
供稿:网友
代码如下:
using system;
using system.reflection;
using system.reflection.emit ;
public class testreflection {
private string file = @"testreflection.exe";
static void main(string[] args) {
testreflection test = new testreflection();
test.displaymodules();
test.displaytypes();
test.displaymethods();
test.invokestaticmethod();
test.invokemethod();
}
//显示所有模块名
public void displaymodules() {
console.writeline("display modules ...");
assembly assembly = assembly.loadfrom(file);
module[] modules = assembly.getmodules();
foreach( module module in modules ) {
console.writeline("module name:" + module.name );
}
}
//显示所有类型名
public void displaytypes() {
console.writeline("display types ...");
assembly assembly = assembly.loadfrom(file);
type[] types = assembly.gettypes();
foreach( type type in types ) {
console.writeline("type name:" + type.fullname );
}
}
//先是一个类型中的所有方法名
public void displaymethods() {
console.writeline("display methods in testreflection type ...");
assembly assembly = assembly.loadfrom(file);
type type = assembly.gettype("testreflection");
methodinfo[] methods = type.getmethods();
foreach(methodinfo method in methods) {
console.writeline("method name:" + method.name);
}
}
//调用一个类中的静态方法
public void invokestaticmethod() {
console.writeline("invoke static method ...");
assembly assembly = assembly.loadfrom(file);
type type = assembly.gettype("testsubclass");
type.invokemember ("sayhello", bindingflags.invokemethod,null,null,new object[]{});
}
//调用一个类中的非静态方法
public void invokemethod() {
console.writeline("invoke method ...");
assembly assembly = assembly.loadfrom(file);
type type = assembly.gettype("testsubclass");
object obj = activator.createinstance(type);
testclass tc = (testclass)obj ;
type.invokemember ("test1", bindingflags.invokemethod,null,tc,new object[]{});
type.invokemember ("test2", bindingflags.invokemethod,null,tc,new object[]{});
}
}
public interface testclass {
void test1();
void test2();
}
public class testsubclass : testclass{
public void test1() {
console.writeline("this is testsubclass.test1");
}
public void test2() {
console.writeline("this is testsubclass.test2");
}
public static void sayhello() {
console.writeline("this is testsubclass.sayhello");
}
}
编译运行后输出:
display modules ...
module name:testreflection.exe
display types ...
type name:testreflection
type name:testclass
type name:testsubclass
display methods in testreflection type ...
method name:gethashcode
method name:equals
method name:tostring
method name:displaymodules
method name:displaytypes
method name:displaymethods
method name:invokestaticmethod
method name:invokemethod
method name:test2
method name:gettype
invoke static method ...
this is testsubclass.sayhello
invoke method ...
this is testsubclass.test1
this is testsubclass.test2