.Net中的反射使用入门[2]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 timmy3310 的 blog

   private string _value;
   public testclass(string value) {
 _value=value;
   }
}
}

type t = type.gettype(“testspace.testclass”);
object[] constructparms = new object[] {“hello”}; //构造器参数
testclass obj = (testclass)activator.createinstance(t,constructparms);

把参数按照顺序放入一个object数组中即可
6、如何获取方法以及动态调用方法
namespace testspace
{
   public class testclass {
     private string _value;
     public testclass() {
     }
     public testclass(string value) {
 _value = value;
     }

     public string getvalue( string prefix ) {
 if( _value==null )
     return "null";
 else
     return prefix+" : "+_value;
      }

      public string value {
 set {
  _value=value;
 }
 get {
  if( _value==null )
   return "null";
  else
   return _value;
 }
      }
   }
}

    上面是一个简单的类,包含一个有参数的构造器,一个getvalue的方法,一个value属性,我们可以通过方法的名称来得到方法并且调用之,如:

//获取类型信息
type t = type.gettype("testspace.testclass");
//构造器的参数
object[] constuctparms = new object[]{"timmy"};
//根据类型创建对象
object dobj = activator.createinstance(t,constuctparms);
//获取方法的信息
methodinfo method = t.getmethod("getvalue");
//调用方法的一些标志位,这里的含义是public并且是实例方法,这也是默认的值
bindingflags flag = bindingflags.public | bindingflags.instance;
//getvalue方法的参数
object[] parameters = new object[]{"hello"};
//调用方法,用一个object接收返回值
object returnvalue = method.invoke(dobj,flag,type.defaultbinder,parameters,null);

    属性与方法的调用大同小异,大家也可以参考msdn

7、动态创建委托
    委托是c#中实现事件的基础,有时候不可避免的要动态的创建委托,实际上委托也是一种类型:system.delegate,所有的委托都是从这个类派生的
    system.delegate提供了一些静态方法来动态创建一个委托,比如一个委托:

namespace testspace {
   delegate string testdelegate(string value);
   public class testclass {
 public testclass() {
         }
         public void getvalue(string value) {
             return value;
         }
    }
}
 
使用示例:
testclass obj = new testclass();
  
//获取类型,实际上这里也可以直接用typeof来获取类型
type t = type.gettype(“testspace.testclass”);
//创建代理,传入类型、创建代理的对象以及方法名称
testdelegate method = (testdelegate)delegate.createdelegate(t,obj,”getvalue”);

string returnvalue = method(“hello”);

 

    到这里,我们简单的讲述了反射的作用以及一些基本的用法,还有很多方面没有涉及到,有兴趣的朋友可以参考msdn。
    很奇怪,很多人都不愿看msdn,其实你想要的答案,99%都可以在里面找到。

本文关键:反射,Reflection
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top