如何使用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
:
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; }
我如何获得所有属性及其价值?
我怎么能得到所有的特性和价值观?
首先,您需要区分字段和属性 。 看起来你在这里有田地。 所以你想要的东西是这样的:
上述就是C#学习教程:如何使用reflection获取类的所有静态属性及其值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public static Dictionary 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)); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/957520.html