[英]How to get all static properties and its values of a class using reflection
我有一個這樣的課:
public class tbl050701_1391_Fields
{
public static readonly string StateName = "State Name";
public static readonly string StateCode = "State Code";
public static readonly string AreaName = "Area Name";
public static readonly string AreaCode = "Area Code";
public static readonly string Dore = "Period";
public static readonly string Year = "Year";
}
我想寫一些語句,返回一個包含以下值的Dictionary<string, string>
:
Key Value
--------------------------------------------
"StateName" "State Name"
"StateCode" "State Code"
"AreaName" "Area Name"
"Dore" "Period"
"Year" "Year"
我有這個代碼來獲取一個屬性值:
public static string GetValueUsingReflection(object obj, string propertyName)
{
var field = obj.GetType().GetField(propertyName, BindingFlags.Public | BindingFlags.Static);
var fieldValue = field != null ? (string)field.GetValue(null) : string.Empty;
return fieldValue;
}
我如何獲得所有房產及其價值?
我如何獲得所有屬性及其價值?
首先,您需要區分字段和屬性 。 看起來你在這里有田地。 所以你想要的東西是這樣的:
public static Dictionary<string, string> GetFieldValues(object obj)
{
return obj.GetType()
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.FieldType == typeof(string))
.ToDictionary(f => f.Name,
f => (string) f.GetValue(null));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.