[.NET]透過Reflection取得類別的所有常數資訊

[.NET]透過Reflection取得類別的所有常數資訊

我們可透過 Reflection 的方式來取得類別的所有常數資訊,以下用範例來說明!

1.建立測試的類別ConstInfoTestDLL.Class1


namespace ConstInfoTestDLL
{
    public class Class1
    {
        public string prop1 { get; set; }
        public const string con1 = "con1_value";
        public const int con2 = 2;
        public const bool con3 = true;

    }
}

 

2.透過 Reflection 來取得類別的常數資訊(參考Getting a list of constants using Reflection),


// using System.Reflection;
// using System.Collections;

/// <SUMMARY>
/// This method will return all the constants from a particular
/// type including the constants from all the base types
/// </SUMMARY>
/// <PARAM NAME="TYPE">type to get the constants for</PARAM>
/// <RETURNS>array of FieldInfos for all the constants</RETURNS>
private FieldInfo[] GetConstants(System.Type type)
{
    ArrayList constants = new ArrayList();

    FieldInfo[] fieldInfos = type.GetFields(
        // Gets all public and static fields

        BindingFlags.Public | BindingFlags.Static |
        // This tells it to get the fields from all base types as well

        BindingFlags.FlattenHierarchy);

    // Go through the list and only pick out the constants
    foreach (FieldInfo fi in fieldInfos)
        // IsLiteral determines if its value is written at 
        //   compile time and not changeable
        // IsInitOnly determine if the field can be set 
        //   in the body of the constructor
        // for C# a field which is readonly keyword would have both true 
        //   but a const field would have only IsLiteral equal to true
        if (fi.IsLiteral && !fi.IsInitOnly)
            constants.Add(fi);

    // Return an array of FieldInfos
    return (FieldInfo[])constants.ToArray(typeof(FieldInfo));
}

private IEnumerable<FieldInfo> GetConstants2(System.Type type)
{

    return type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy).Where(x => x.IsLiteral && !x.IsInitOnly);

}

 

所以我們可透過以上定義的Method來取得ConstInfoTestDLL.Class1的常數資訊,如下,


private void button1_Click(object sender, EventArgs e)
{
    FieldInfo[] constInfos = GetConstants(typeof(ConstInfoTestDLL.Class1));
    foreach (FieldInfo f in constInfos)
    {
        string fInfo = "name:" + f.Name + ",value:" + f.GetValue(null).ToString() 
        + ",type:" + f.FieldType.ToString(); 
    }
    foreach (FieldInfo f in GetConstants2(typeof(ConstInfoTestDLL.Class1)) )
    {
        string fInfo = "name:" + f.Name + ",value:" + f.GetValue(null).ToString() 
        + ",type:" + f.FieldType.ToString();
    }
}

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^