c#中的Type类

     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();
        }
    }
}

运行结果

  • 17
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值