天天看點

反射入門

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

namespace 反射
{
    class Program
    {
        static void Main(string[] args)
        {
            //擷取反射的方法有兩種
            //1.有對象使用對象擷取反射
            //MyClass mc = new MyClass();
            //Type type = mc.GetType();

            //沒有對象使用typeof擷取反射
            Type type = typeof(MyClass);

            //擷取所有非私有屬性
            PropertyInfo[] propertyInfo = type.GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                Console.WriteLine(propertyInfo[i].Name);
            }


            //擷取非私有字段
            FieldInfo[] fieldInfos = type.GetFields();
            for (int i = 0; i < fieldInfos.Length; i++)
            {
                Console.WriteLine(fieldInfos[i].Name);
            }



            MethodInfo methodInfo = type.GetMethod("SayHi");
            MethodBody methodBody = methodInfo.GetMethodBody();
            Console.WriteLine(methodBody);
            

            Console.ReadKey();

        }
    }

    class MyClass
    {
        public string _gtfs;
        public string _btfs;

        public string Name
        {
            get;
            set;
        }
        public void SayHi()
        {
            Console.WriteLine("Hi~~~");
        }

        private void SayHello()
        {
            Console.WriteLine("Hello~~~");
        }
    }
}