代码之家  ›  专栏  ›  技术社区  ›  MythicalCode_

如何使用反射获取对象中的所有变量?

  •  2
  • MythicalCode_  · 技术社区  · 6 年前

    foreach (var property in PropertiesOfType<string>(propertiesJSON))
    {
        dictionary.Add(property.Key, property.Value);
    }
    

    在这段代码中, 是我需要的对象。以下是PropertiesOfType方法:

    public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
    {
        return from p in obj.GetType().GetProperties()
               where p.PropertyType == typeof(T)
               select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
    }
    

    var propertiesJSON = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.PropertiesJSON>(content);
    

    这是类本身:

    class PropertiesJSON
    {
        public string botToken;
        public bool girl;
        public int age;
        public string[] hi;
        public string test;
    }
    

    1 回复  |  直到 6 年前
        1
  •  6
  •   Sweeper    6 年前

    这些:

    public string botToken;
    public bool girl;
    public int age;
    public string[] hi;
    public string test;
    

    public string botToken { get; }
    public bool girl  { get; }
    public int age  { get; }
    public string[] hi  { get; }
    public string test  { get; }
    

    GetFields 而不是 GetProperties

    return from p in obj.GetType().GetFields()
           where p.FieldType == typeof(T)
           select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
    

    我建议您将字段更改为所有属性。