一、概述
Type表示类型,可以获得:类、接口、数组、值、枚举、类型参数、泛型等类的类型。我们可以通过Type得到某个类型的许多信息,这在使用反射时是极为有用的。
二、主要内容
1.获取给定类型的Type有3种方式:
a.使用typeof运算符,如Type t = typeof(int);
b.使用对象实例的GetType()方法,如:int i; Type t = i.GetType();
c.使用 Type类的静态方法GetType(),如Type t =Type.GetType("System.Double");//获取具有指定名称的type,该方法有六个重载。
2.Type的属性:
Name:数据类型名;
FullName:数据类型的完全限定名,包括命名空间;
Namespace:数据类型的命名空间;
a.使用typeof运算符,如Type t = typeof(int);
b.使用对象实例的GetType()方法,如:int i; Type t = i.GetType();
c.使用 Type类的静态方法GetType(),如Type t =Type.GetType("System.Double");//获取具有指定名称的type,该方法有六个重载。
2.Type的属性:
Name:数据类型名;
FullName:数据类型的完全限定名,包括命名空间;
Namespace:数据类型的命名空间;
IsClass:是否是引用类型;
IsValueType:是否是值类型;
BaseType:直接基本类型,即直接父类。
UnderlyingSystemType:映射类型;
BaseType:直接基本类型,即直接父类。
UnderlyingSystemType:映射类型;
注:映射类型指的是CTS(通用类型系统)中的类型。CTS保证了不同程序语言的对象能够交互,例如:VB中integer和C#中的int32最后都会转换为CTS中的system.int32类型。
3.Type的方法:
GetMethod(string MethodName):返回某个方法的信息;
GetMethods():返回所有公共方法的信息。
3.Type的方法:
GetMethod(string MethodName):返回某个方法的信息;
GetMethods():返回所有公共方法的信息。
GetFields():返回所有公共字段信息。
GetMembers();返回所有的公共成员信息,包括字段,属性,方法,事件等。
。。。
4.下面看一个关于Type的例子
TestType.cs:
- using System;
- using System.Reflection;
- namespace gameloft9
- {
- public class TestType
- {
- public static void Main()
- {
- //基本数据类型
- Type t = typeof(int);
- // t=Type.GetType("int");
- //int i;
- //t = i.GetType();
- //属性
- Console.WriteLine("intType.Name = " + intType.Name);
- Console.WriteLine("intType.Namespace = " + intType.Namespace);
- Console.WriteLine("intType.IsClass = " + intType.IsClass);
- Console.WriteLine("intType.IsValueType = " + intType.IsValueType);
- //方法
- /*MethodInfo属于System.Reflection空间,同样还有:
- FieldInofSystem.Reflection.Assembly
System.Reflection.MemberInfo
System.Reflection.EventInfo
System.Reflection.FieldInfo
System.Reflection.MethodBase
System.Reflection.ConstructorInfo
System.Reflection.PropertyInfo*/ - MethodInfo[] methods = intType.GetMethods();
- foreach (MethodInfo i in methods)
- {
- //申明该类型的类+成员类型(这里肯定是method类型)+方法名
- Console.WriteLine(i.DeclaringType + " " + i.MemberType + " " + i.Name);
- }
- }
- }
- }
- 关于反射可以参考博客:
- http://blog.youkuaiyun.com/tonglian/article/details/2271066
- 参考博客:
- http://blog.youkuaiyun.com/byondocean/article/details/6550457