1. 程式人生 > >C#中的反射舉例—FieldInfo

C#中的反射舉例—FieldInfo

如下程式:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        public int myField1 = 0;
        protected string myField2 = null;
        public static void Main()
        {
            FieldInfo[] myFieldInfo;
            Type myType = typeof(Program);
            // Get the type and fields of FieldInfoClass.
            myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
                | BindingFlags.Public);
            Console.WriteLine("\nThe fields of " +
                "FieldInfoClass are \n");
            // Display the field information of FieldInfoClass.
            for (int i = 0; i < myFieldInfo.Length; i++)
            {
                Console.WriteLine("\nName            : {0}", myFieldInfo[i].Name);
                Console.WriteLine("Declaring Type  : {0}", myFieldInfo[i].DeclaringType);
                Console.WriteLine("IsPublic        : {0}", myFieldInfo[i].IsPublic);
                Console.WriteLine("MemberType      : {0}", myFieldInfo[i].MemberType);
                Console.WriteLine("FieldType       : {0}", myFieldInfo[i].FieldType);
                Console.WriteLine("IsFamily        : {0}", myFieldInfo[i].IsFamily);
            }
        }
    }
}

這個類中有兩個屬性myField1和myField2,使用陣列FieldInfo得到成員變數的一些相關資訊,如型別,訪問屬性等等。

輸入結果: