c#中的Type类

时间:2021-03-31 11:48:45   收藏:0   阅读:0

  Type类,用来包含类型的特性。对于程序中的每一个类型,都会有一个包含这个类型的信息的Type类的对象,类型信息包含数据,属性和方法等信息。

1.生成Type对象


      有两种方法可以生成Type类的对象:一种是Typeof(类名),一种是对象调用GetType()函数。

  Type type = typeof(Person);

  Person person = new Person();
  Type type2 = person.GetType();


2.获取类的信息


//类的名称
string name = type.Name;
//类的命名空间
string space = type.Namespace;
//类的程序集
Assembly assembly = type.Assembly;
//类的共有字段
FieldInfo[] fieldInfos = type.GetFields();
//类的属性
PropertyInfo[] propertyInfos = type.GetProperties();
//类的方法
MethodInfo[] methodInfos = type.GetMethods();


3.代码实例

using System;
using System.Reflection;

namespace ConsoleApp2
{
public class Person
{
public int Id;
public string Name;
public int Age { get; set; }
public string Department { get; set; }

public void Print()
{
string str = string.Format("{0} {1} {2} {3}", Id, Name, Age, Department);
Console.WriteLine(str);
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
Type type = person.GetType();

//类的名称
Console.WriteLine("类的名称: " + type.Name); 
//类的命名空间
Console.WriteLine("类的命名空间: " + type.Namespace);

//类的共有字段
Console.Write("类的共有字段: ");
FieldInfo[] fieldInfos = type.GetFields();
foreach (FieldInfo info in fieldInfos)
{
Console.Write(info.Name + " ");
}
Console.WriteLine();

//类的属性
Console.Write("类的属性: ");
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (PropertyInfo info in propertyInfos)
{
Console.Write(info.Name + " ");
}
Console.WriteLine();

//类的方法
Console.Write("类的方法: ");
MethodInfo[] methodInfos = type.GetMethods();
foreach (MethodInfo info in methodInfos)
{
Console.Write(info.Name + " ");
}
Console.WriteLine();

//类的程序集
Assembly assembly = type.Assembly;
Console.WriteLine("类的程序集: " + assembly.FullName);

//当前程序集下所有的类型
Console.Write("当前程序集下所有的类型: ");
Type[] types = assembly.GetTypes();
foreach (Type item in types)
{
Console.Write(item + " ");
}
Console.WriteLine();

Console.ReadKey();
}
}
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!