C#反射(Type類)使用

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Reflector_Type
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             Type類
             */

            //1.怎麼獲取一個類型的Type(該類型的類型元數據)
            MyClass m = new MyClass();
            //獲得了類型MyClass的對應Type(有對象)
            Type t1 = m.GetType();

            //獲得了類型MyClass的對應Type(通過Typeof關鍵字,無須獲取Myclass類型對象就可以拿到MyclassType對象)
            Type t2 = typeof(MyClass);

            //2.拿到Type類能幹什麼?
            Type TypeMyclass = typeof(MyClass);

            //可以獲取當前的父類 TypeMyclass.BaseType.ToString()
            Console.WriteLine(TypeMyclass.BaseType.ToString());

            //獲取當前類型中所有的字段信息
            //這裏只能獲取非私有的字段信息
            FieldInfo [] fileds = TypeMyclass.GetFields();
            for (int i = 0; i < fileds.Length; i++)
            {
                Console.WriteLine(fileds[i].Name.ToString());
            }

            //獲取當前類型中的所有屬性
            PropertyInfo [] propinfo = TypeMyclass.GetProperties();
            for (int i = 0; i < propinfo.Length; i++)
            {
                Console.WriteLine(propinfo[i].Name.ToString());
            }

            //獲取Type中的方法
            MethodInfo [] Methods = TypeMyclass.GetMethods();
            for (int i = 0; i < Methods.Length; i++)
            {
                Console.WriteLine(Methods[i].Name.ToString());
            }

            //Z獲取Type中所有的成員
            MemberInfo [] Members = TypeMyclass.GetMembers();

            Console.ReadKey();
        }
    }

    public class MyClass
    {
        public int field1;

        public string field2;


        public string Name { get; set; }

        public string  Address { get; set; }

        public void Say()
        {
            Console.WriteLine("十方無影像,六道絕蹤跡");
        }

        private void Say2()
        {
            Console.WriteLine("跳出三界外,不在五行中");
        }


    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章