2015-11-02 46 views
4

我有一個常量類。我有一些字符串,可以與其中一個常量的名稱相同或不相同。按名稱獲得常量值

因此類常量ConstClass有一些public constconst1, const2, const3...

public static class ConstClass 
{ 
    public const string Const1 = "Const1"; 
    public const string Const2 = "Const2"; 
    public const string Const3 = "Const3"; 
} 

要檢查類包含const的名字我已經嘗試下一個:

var field = (typeof (ConstClass)).GetField(customStr); 
if (field != null){ 
    return field.GetValue(obj) // obj doesn't exists for me 
} 

不知道這是否是真的正確的方法要做到這一點,但現在我不知道如何獲得價值,導致.GetValue方法需要obj類型ConstClass(ConstClass是靜態的)

+1

你能重新組織你的問題,並顯示你的代碼,以便更容易遵循? (而不是*描述*你的代碼,它很難*遵循) – Amit

+2

而不是使用一些常量和反射來得到它們,我強烈建議使用'Dictionary '。這樣更高效,更易於維護,而且更具可讀性。 –

回答

7

要使用反射來獲取靜態類型的字段值或調用成員,請將null作爲實例引用。

下面是一個簡短LINQPad程序演示:

void Main() 
{ 
    typeof(Test).GetField("Value").GetValue(null).Dump(); 
    // Instance reference is null ----->----^^^^ 
} 

public class Test 
{ 
    public const int Value = 42; 
} 

輸出:

42 

請注意,如圖所示的代碼將不正常的字段和const字段之間進行區分。

要做到這一點,你必須檢查該字段的信息還包含標誌Literal

下面是一個簡短LINQPad程序,只檢索常量:

void Main() 
{ 
    var constants = 
     from fieldInfo in typeof(Test).GetFields() 
     where (fieldInfo.Attributes & FieldAttributes.Literal) != 0 
     select fieldInfo.Name; 
    constants.Dump(); 
} 

public class Test 
{ 
    public const int Value = 42; 
    public static readonly int Field = 42; 
} 

輸出:

Value 
2
string customStr = "const1"; 

if ((typeof (ConstClass)).GetField(customStr) != null) 
{ 
    string value = (string)typeof(ConstClass).GetField(customStr).GetValue(null); 
} 
+0

你打算解釋你的代碼,以及如何解決這個問題? –

+1

不,不是真的很自我解釋。 OP詢問如何獲得const變量的值,那就是答案。 –

-1

typeof(YourClass).GetField(PropertyNameString).GetValue(null)就足以讓va lue的財產

+0

單線解決方案應在評論中。 – Rumit

+0

雖然此代碼可能回答此問題,但爲何和/或代碼如何回答此問題提供了其他上下文,這可以提高其長期價值。 – rollstuhlfahrer