C# 反射手記

從代碼中學習吧

可以把 TestInterface 塊裏的方法放進 Main 執行來對應的理解

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

namespace ReflectionLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintClassStaticMethodInfo();
        }

        #region TestInterface

        #region GetMembers
        private static void PrintClassPublicInfo(Type varType)
        {
            //返回公開成員;
            MemberInfo[] tempMemInfos = varType.GetMembers();
            ShowMemberConsoleInfo(tempMemInfos);
        }
        private static void PrintClassAllInfo(Type varType)
        {
            //包含非公開、包含實例成員、包含公開;
            //此處含父類的成員;
            MemberInfo[] tempMemInfos = varType.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
            ShowMemberConsoleInfo(tempMemInfos);
        }
        private static void PrintClassSelfInfo(Type varType)
        {
            //包含非公開、包含實例成員、包含公開;
            //BindingFlags.DeclaredOnly 表明 不含父類的成員;
            MemberInfo[] tempMemInfos = varType.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            ShowMemberConsoleInfo(tempMemInfos);
        }

        private static void PrintClassSelfInclueStaticInfo(Type varType)
        {
            //包含非公開、包含實例成員、包含公開;
            //BindingFlags.DeclaredOnly 表明 不含父類的成員;
            MemberInfo[] tempMemInfos = varType.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static);
            ShowMemberConsoleInfo(tempMemInfos);
        }
        #endregion

        #region GetFields

        private static void PrintClassFieldsInfo()
        {
            Type tempType = typeof(RefClass);
            RefClass tempRc = new RefClass();
            tempRc.pIntMember = 3;

            FieldInfo[] tempFieInfos = tempType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static);
            foreach (FieldInfo tempInfo in tempFieInfos)
            {
                if (tempInfo.Name == "mIntMember")
                {
                    tempInfo.SetValue(tempRc,999);
                }
                if (tempInfo.Name == "<mIntProperty>k__BackingField")
                {
                    //屬性方法;
                    tempInfo.SetValue(tempRc, 777);
                }
                Console.WriteLine("名稱: " + tempInfo.Name + "  --  類型: " + GetMemberType(tempInfo.MemberType) + " - 值: " + tempInfo.GetValue(tempRc));
            }
            Console.ReadKey();
        }

        private static void PrintClassPropertyInfo()
        {
            Type tempType = typeof(RefClass);
            RefClass tempRc = new RefClass();
            tempRc.pIntMember = 3;

            PropertyInfo[] tempPropertyInfos = tempType.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static);
            foreach (PropertyInfo tempInfo in tempPropertyInfos)
            {
                MethodInfo tempGetInfo = tempInfo.GetGetMethod(true);
                Console.WriteLine("get方法的名稱{0}  返回值類型:{1}  參數數量:{2}  MSIL代碼長度:{3} 局部變量數量:{4}", 
                    tempGetInfo.Name, tempGetInfo.ReturnType.ToString(),
                    tempGetInfo.GetParameters().Count(),
                    tempGetInfo.GetMethodBody().GetILAsByteArray().Length, 
                    tempGetInfo.GetMethodBody().LocalVariables.Count);

                MethodInfo tempSetInfo = tempInfo.GetSetMethod(true);
                Console.WriteLine("get方法的名稱{0}  返回值類型:{1}  參數數量:{2}  MSIL代碼長度:{3} 局部變量數量:{4}", 
                    tempSetInfo.Name, tempSetInfo.ReturnType.ToString(),
                    tempSetInfo.GetParameters().Count(),
                    tempSetInfo.GetMethodBody().GetILAsByteArray().Length,
                    tempSetInfo.GetMethodBody().LocalVariables.Count);

               tempSetInfo.Invoke(tempRc, new object[] { 666 });
               object obj = tempGetInfo.Invoke(tempRc, null);
               Console.WriteLine("方法名:{0}  內部值:{1}", tempInfo.Name, obj);
            }
            Console.ReadKey();
        }

        #endregion

        #region StaticMethods
        private static void PrintClassStaticMethodInfo()
        {
            Type tempType = typeof(RefClass);
            RefClass tempRc = new RefClass();
            tempRc.pIntMember = 3;

            MethodInfo[] tempPropertyInfos = tempType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static);
            foreach (MethodInfo tempInfo in tempPropertyInfos)
            {
                if (tempInfo.GetParameters().Count() > 0 && tempInfo.GetParameters()[0].ParameterType == typeof(string) )
                {
                    object obj = tempInfo.Invoke(tempRc, new[] { "123" });
                    MethodBody mbody = tempInfo.GetMethodBody();
                    Console.WriteLine("擁有參數的方法名:{0}  返回值類型:{1}  參數1類型:{2}  參數1名稱:{3}  方法調用後返回的值:{4}",
                        tempInfo.Name,
                        tempInfo.ReturnType.ToString(),
                        tempInfo.GetParameters()[0].ParameterType.ToString(),
                        tempInfo.GetParameters()[0].Name,
                        obj.ToString());
                }
                else
                {
                    MethodBody mbody = tempInfo.GetMethodBody();
                    Console.WriteLine("沒有參數的方法名:{0}  返回值類型:{1}",
                        tempInfo.Name,
                        tempInfo.ReturnType.ToString());
               }
            }
            Console.ReadKey();
        }
        #endregion

        #endregion

        #region LogicBusiness
        private static void ShowMemberConsoleInfo(MemberInfo[] varMemInfos)
        {
            foreach (MemberInfo tempInfo in varMemInfos)
            {
                Console.WriteLine("名稱: " + tempInfo.Name + "  --  類型: " + GetMemberType(tempInfo.MemberType));
            }
            Console.ReadKey();
        }


        private static string GetMemberType(MemberTypes varMemType)
        {
            string tempTypeStr = string.Empty;
            switch (varMemType)
            {
                case MemberTypes.Field:
                    {
                        tempTypeStr = "字段";
                    }break;
                case MemberTypes.Method:
                    {
                        tempTypeStr = "方法";
                    }break;
                case MemberTypes.Property:
                    {
                        tempTypeStr = "屬性";
                    }break;
                case MemberTypes.Constructor:
                    {
                        tempTypeStr = "構造函數";
                    } break;
                case MemberTypes.Custom:
                    {
                        tempTypeStr = "自定義成員";
                    } break;
                case MemberTypes.Event:
                    {
                        tempTypeStr = "事件";
                    } break;
                case MemberTypes.NestedType:
                    {
                        tempTypeStr = "嵌套";
                    } break;
                case MemberTypes.TypeInfo:
                    {
                        tempTypeStr = "類型";
                    } break;
                default:
                    {
                        tempTypeStr = "未知";
                    }break;
            }
            return tempTypeStr;
        }

        #endregion

    }

    #region DefineInfo

    public class RefClass
    {
        private int mIntMember;
        private int mIntProperty { get; set; }
        protected int mProteInt;
        public int pIntMember { get; set; }

        public CustomClassOne mCustomClass;

        public void AnyOne()
        {

        }
        public static void ThisIsStaticMethodOne()
        {

        }
        public static void ThisIsStaticMethodTwo()
        {

        }

        public static string HadReturnValueA(string varStr)
        {
            int tempIntA;
            int tempIntB;
            return varStr;
        }
        public static string HadReturnValueB(string varStr)
        {
            string tempStr;
            return varStr;
        }
    }

    public class CustomClass
    {
        public int MCustomInt;

    }

    public class CustomClassOne : CustomClass
    {
        public int MCustomInt;
        public static CustomClassTwo mCustomClassTwo;
    }

    public class CustomClassTwo : CustomClass
    {
        public int MCustomInt;

    }

    #endregion

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