码迷,mamicode.com
首页 > Windows程序 > 详细

C#的Type对象的简单应用

时间:2020-06-14 17:05:36      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:loading   添加   png   com   void   eth   pre   vat   私有   

通过Type对象可以获取类中所有的公有成员

直接贴代码:

class MyClass

    {

        private string name;

        private int id;

        public string city;

        public int number;

 

        public string yifu { get;private set; }//对外部只读不取

 

        private string kuzi { get; set; }

 

        public void setYifu(string yifu)

        {

            this.yifu = "yifu";

 

        }

 

        public void method1() { }

 

        private void method2() { }

}

static void Main(string[] args)

        {

            //string Name = "testing1";

            //Type type = typeof(Name);//不成立,type只能指向类

 

            MyClass myclass = new MyClass();

            Type type = myclass.GetType();

            Console.WriteLine(type.Assembly);//获取所在程序集

            Console.WriteLine(type.Namespace);//获取所在命名空间

            Console.WriteLine(type.Name);//获取类名

            FieldInfo[] FieldArray = type.GetFields();//将类中公有字段添加进array中,私有的没有权限所以访问不到

            foreach (var fInfo in FieldArray)

            {

                Console.WriteLine(fInfo.Name);//获取字段名

            }

 

            PropertyInfo[] propertyArray = type.GetProperties();

            //PropertyInfo propertyName = type.GetProperty("yifu");

            foreach (var pInfo in propertyArray)//获取公有属性

            {

                Console.WriteLine(pInfo.Name);//获取属性名

            }

 

            MethodInfo[] methodArray = type.GetMethods();

            foreach (var mInfo in methodArray)//获取公有方法

            {

                Console.WriteLine(mInfo.Name);//获取方法名,会输出包括系统预定义的如ToString,GetHashCode等方法

            }

            //通过Type对象可以获取类中所有的公有成员

        }

输出结果:

技术图片

 

C#的Type对象的简单应用

标签:loading   添加   png   com   void   eth   pre   vat   私有   

原文地址:https://www.cnblogs.com/qjns/p/13125224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!