C#反射

来源:互联网 发布:房源中介系统源码 编辑:程序博客网 时间:2024/04/28 05:31
namespace _09反射1_
{
    class Program
    {
        static void Main(string[] args)
        {
            //请写一段程序输出:Person类中有几个方法,几个属性。以及每个方法名和属性名。
            // Person p = new Person();


            //获取Person类的“档案”
            //其实这个“档案”就是描述Person类型的一个类。【类型元数据】
            // Type typePerson = typeof(Person);
            Person p = new Person();
            Type typePerson = p.GetType();
            Console.WriteLine("Person的父类:{0}", typePerson.BaseType.ToString());


            Console.WriteLine("Person类中的属性:");
            //获取Person类中的所有的属性
            PropertyInfo[] pinfo = typePerson.GetProperties();
            for (int i = 0; i < pinfo.Length; i++)
            {
                Console.WriteLine(pinfo[i].Name);
            }


            Console.WriteLine("Person类中的方法:");


            MethodInfo[] minfo = typePerson.GetMethods();


            
            for (int i = 0; i < minfo.Length; i++)
            {
                Console.WriteLine(minfo[i].Name);
            }


            //反射里面最重要的就是要获取这个类型对应的Type
            //获取这个Type以后,就可以根据这个Type,获取当前类型的所有相关信息。




            Console.ReadKey();






        }
    }


    public class Person
    {
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
        public string Email
        {
            get;
            set;
        }




        public void SayHi()
        {
            Console.WriteLine("hi!!");
        }
    }
}
0 0
原创粉丝点击