《ASP.NET本质论》 反射

来源:互联网 发布:淘宝佣金平台 编辑:程序博客网 时间:2024/05/17 12:56

        在 .NET 环境下,System.Type 是反射Reflection 的基础,提供了访问元数据的主要方式,这个类定义在命名空间 System 下。
 

[SerializableAttribute][ClassInterfaceAttribute(ClassInterfaceType.None)][ComVisibleAttribute(true)]public abstract class Type : MemberInfo, _Type, IReflect

        通过 Type 类型的静态方法,GetType 我们可以通过一个字符串形式的类型描述获取特定类型的类型对象。

public static Type GetType(string typeName)

        typeName可以是简单的类型名、包含眼命名空间的类型名,或者包含程序集名称规范的复杂名称。
        如果 typeName 仅仅包含 Type 的名称,则此方法现在调用对象的程序集中进行搜索,然后在 mscorlib.dll 程序集中进行搜索。如果typeName是用部分或者完成的程序集名称完全限定的,则此方法将在指定的程序集中进行搜索。
        例如,取得字符串的类型对象的引用,由于字符串类型定义在程序集 mscorlib.dll 中,可以如下获得。
System.Type type = System.Type.GetType("System.String");        Response.Write(type);

       通过 GetMethods 可以取得这个类中所有公共的方法,方法的类型通过 System.Reflection.MethodInfo 进行描述。
       
System.Reflection.MethodInfo[] methods = type.GetMethods();        foreach( System.Reflection.MethodInfo m in methods )        {            Response.Write("<br/>"+m.Name);        }

        通过 GetMethod 方法,我们可以去的特定的方法对象,GetMethod 需要我们提供方法的名称以及方法的参数描述,方法的参数通过一个类型的数组定义。
     
string methodName = "Sbustring";        Type[] typeArray = new Type[]         {            typeof(int),            typeof(int)        };        System.Type type = System.Type.GetType("System.String");        System.Reflection.MethodInfo m=type.GetMethod(methodName,typeArray);

  通过反射,我们可以不通过new 关键字,而直接创建一个特定类型的对象实例。
        例如,我们希望通过字符串对象的构造函数 public String( char[] value) 来创建一个字符串对象的实力,那么,可以通过System.Activator创建。

char[] chars = "Hello,world.".ToCharArray();        string s = System.Activator.CreateInstance(type, chars) as string;

        最后,我们可以通过反射调用字符串对象实例上的 Substring 方法,获取字符串的一个子串。这可以通过 MethodInfo 的Invoke 方法完成。
         
string resule = m.Invoke(s, new object[] { 0, 5 }) as string;

原创粉丝点击