如何使用反射获取类的所有静态属性及其值 [英] How to get all static properties and its values of a class using reflection

查看:307
本文介绍了如何使用反射获取类的所有静态属性及其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的类:

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> 具有以下值:

I want to write some statement that returns a Dictionary<string, string> that has these values:

Key                            Value
--------------------------------------------
"StateName"                    "State Name"
"StateCode"                    "State Code"
"AreaName"                     "Area Name"
"Dore"                         "Period"
"Year"                         "Year"

我有以下代码可获取一个物业的价值:

I have this code for getting one property value:

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;
}

如何获取所有属性及其值?

How I can get all properties and their values?

推荐答案


如何获取所有属性及其值?

how I can get all properties and their values?

首先,您需要区分字段属性。好像您在这里有字段。因此,您需要这样的东西:

Well to start with, you need to distinguish between fields and properties. It looks like you've got fields here. So you'd want something like:

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));
}

这篇关于如何使用反射获取类的所有静态属性及其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆