How to get all static properties and its values of a class using reflection

前端 未结 1 1679
予麋鹿
予麋鹿 2020-12-09 14:48

I hava a class like this:

public class tbl050701_1391_Fields
{
    public static readonly string StateName = \"State Name\";
    public static readonly strin         


        
相关标签:
1条回答
  • 2020-12-09 15:18

    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));
    }
    
    0 讨论(0)
提交回复
热议问题