c#之反射_FieldInfo_GetField_

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

//要檢查的類
public class Demo
{
    // Make three fields:
    // The first field is private.
    private string m_field = "String A";//要檢查類的成員屬性

    // The second field is public.
    public string Field = "String B";

    // The third field is public const (hence also literal and static),
    // with a default value.
    public const string FieldC = "String C";
}

//實施檢查的類
public class Myfieldattributes
{
    public static void Main()
    {
        Console.WriteLine("\nReflection.FieldAttributes");
        //例項化檢查類
        Demo d = new Demo();

        // Get a Type object for Demo, and a FieldInfo for each of
        // the three fields. Use the FieldInfo to display field
        // name, value for the Demo object in d, and attributes.
        //
        //獲取要檢查類的類物件mytype
        Type myType = typeof(Demo);//注:typeof的引數直接是類名,不用""

        //基於以上mytype,用方法getfield返回型別fieldinfo,

        FieldInfo fiPrivate = myType.GetField("m_field",
            BindingFlags.NonPublic | BindingFlags.Instance);//注意引數的bindingflags,要對應起來
       
        //如下方法能數為object及fieldinfo型別
        //d是要測試類的例項化物件
        //此方法的引數為:要測試的例項化物件和要測試類的成員屬性

        DisplayField(d, fiPrivate);//呼叫方法displayfield顯示上述加工的結果

        FieldInfo fiPublic = myType.GetField("Field",
            BindingFlags.Public | BindingFlags.Instance);
        DisplayField(d, fiPublic);

        FieldInfo fiConstant = myType.GetField("FieldC",
            BindingFlags.Public | BindingFlags.Static);
        DisplayField(d, fiConstant);
        Console.ReadKey();
    }

    static void DisplayField(Object obj, FieldInfo f)
    {
        // Display the field name, value, and attributes.
        //譯上:顯示屬性名稱,屬性值,列
        //{0},{1},{2}分別對應f.name,f.getvalue(obj),f.attributes
        // \"為轉義符表示",因為要輸出"
        // FieldAttributes是一個列舉型別,返回要檢查類或物件的成員所有相關資訊,比如是否private,public,literal,hashdefault等
        Console.WriteLine("{0} = \"{1}\"; attributes: {2}",
            f.Name, f.GetValue(obj), f.Attributes);//fieldinfo.getvalue(object)是:返回給定物件的屬性的值
    }
}

/* This code example produces the following output:

Reflection.FieldAttributes
m_field = "String A"; attributes: Private
Field = "String B"; attributes: Public
FieldC = "String C"; attributes: Public, Static, Literal, HasDefault
 */

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

相關文章