天天看点

C# Type 类

名词解释:

Type类,是一个用来存储类型的特性和信息的类。对于程序中的每一个类型,都会有他自己的类信息,而根据Type提供的属性和方法获得这个类型的一切信息,包括字段,属性,事件,参数,构造函数等。

生成Type 对象

(1)Type t = typeof(String),通过获取具体类的type。注意typeof 是运算符合,typeof(x)中的x 是具体的必须是具体的类名、类型名称等(int ,string,自定义类等等),不可以是变量名称。

(2)Type t = value.GetType(),对象调用基类基类System.Object的方法的方法 GetType。

Type常用信息:

这个主要可以具体看Type类文档, 这个类型 的所有信息基本都可以获取的。这里列些常用的:

/类的名称    
string name = type.Name;           
//类的命名空间
string space = type.Namespace;
//类的程序集
Assembly assembly = type.Assembly;
//类的共有字段
FieldInfo[] fieldInfos = type.GetFields();
//获取具体的共有字段
FieldInfo fieldInfos = type.GetField(string name);
//类的属性
PropertyInfo[] propertyInfos = type.GetProperties();
//类的方法
MethodInfo[] methodInfos = type.GetMethods();
//具体的方法
MethodInfo methodInfo = type.GetMethod(string name);
//所有公共成员
 MemberInfo[] memberInfo = type.GetMembers()
//获取具体共总成员
MemberInfo[] memberInfo = type.GetMember(string name);
           

FieldInfo:

FieldInfo.GetValue(Object) Method 获取的属性的值,参数Object:将返回其字段值的对象。