c#之反射_Type_Fieldinfo[]小記

wisdomone1發表於2011-08-20
using System;
using System.Reflection;//反射

public class FieldInfoClass
{
    public int myField1 = 0;
    protected string myField2 = null;//保護成員,class and subclass can access
    public static void Main() //static main method
    {
        FieldInfo[] myFieldInfo;//陣列類
        Type myType = typeof(FieldInfoClass);//自生類的類型別提取
        // Get the type and fields of FieldInfoClass.

        //基於以上自生類型別提取類的屬性,返回fieldinfo[]

        //由type.getfields方法返回fieldinfo型別,由此可以提取類的相關屬性定義資訊
        //方法參數列示SEARCH的範圍
        myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance
            | BindingFlags.Public);
        Console.WriteLine("\nThe fields of " +
            "FieldInfoClass are \n");
        // Display the field information of FieldInfoClass.

        //fieldinfo[].length提取類型別中屬性的個數
        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);
            Console.ReadKey();
        }
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-705449/,如需轉載,請註明出處,否則將追究法律責任。

相關文章