How to get the list of properties of a class?

后端 未结 10 1341
陌清茗
陌清茗 2020-11-21 09:48

How do I get a list of all the properties of a class?

10条回答
  •  花落未央
    2020-11-21 10:37

    You can use Reflection to do this: (from my library - this gets the names and values)

    public static Dictionary DictionaryFromType(object atype)
    {
        if (atype == null) return new Dictionary();
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        Dictionary dict = new Dictionary();
        foreach (PropertyInfo prp in props)
        {
            object value = prp.GetValue(atype, new object[]{});
            dict.Add(prp.Name, value);
        }
        return dict;
    }
    

    This thing will not work for properties with an index - for that (it's getting unwieldy):

    public static Dictionary DictionaryFromType(object atype, 
         Dictionary indexers)
    {
        /* replace GetValue() call above with: */
        object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
    }
    

    Also, to get only public properties: (see MSDN on BindingFlags enum)

    /* replace */
    PropertyInfo[] props = t.GetProperties();
    /* with */
    PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
    

    This works on anonymous types, too!
    To just get the names:

    public static string[] PropertiesFromType(object atype)
    {
        if (atype == null) return new string[] {};
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        List propNames = new List();
        foreach (PropertyInfo prp in props)
        {
            propNames.Add(prp.Name);
        }
        return propNames.ToArray();
    }
    

    And it's just about the same for just the values, or you can use:

    GetDictionaryFromType().Keys
    // or
    GetDictionaryFromType().Values
    

    But that's a bit slower, I would imagine.

提交回复
热议问题