1. 程式人生 > >C#反射的學習(一)--獲得成員資訊

C#反射的學習(一)--獲得成員資訊

using UnityEngine;
using System.Collections;
using System;
using System.Reflection;

public class Reflection_Test : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        Type t = typeof(Person);
        
        //輸出成員的型別
        //輸出成員的型別
        //public delegate TResult Func(T arg);
        //封裝一個具有一個引數並返回 TResult 引數指定的型別值的方法
        //這裡可以學習到 http://www.cnblogs.com/pnljs/p/3792407.html
        Func getType = (x) =>
        {
            switch (x)
            {
                case MemberTypes.Field:
                    return "欄位";
                case MemberTypes.Method:
                    return "方法";
                case MemberTypes.Property:
                    return "屬性";
                default: return "未知";
            }
        };

        MemberInfo[] minfos3 = t.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static);
        foreach (MemberInfo m in minfos3)
        {
            Debug.Log(m.Name + "  型別: " + getType(m.MemberType));
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}
列印輸出: