2009-08-17 61 views

回答

20

試着檢查FieldInfo.Attributes是否包含FieldAttributes.Literal。我沒有檢查它,但它聽起來權利...

(我不認爲你可以得到只到GetFields單個呼叫常數,但你可以過濾返回的結果的方式。)

34
type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral); 
0

從.NET 4.5開始,你可以做到這一點

public class ConstTest 
{ 
    private const int ConstField = 123; 

    public int GetValueOfConstViaReflection() 
    { 
     var fields = this.GetType().GetRuntimeFields(); 
     return (int)fields.First(f => f.Name == nameof(ConstField)).GetValue(null); 
    } 
} 

我檢查,它看起來像領域擁有所有私人consts。