How to get the list of properties of a class?

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

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

相关标签:
10条回答
  • 2020-11-21 10:29

    That's my solution

    public class MyObject
    {
        public string value1 { get; set; }
        public string value2 { get; set; }
    
        public PropertyInfo[] GetProperties()
        {
            try
            {
                return this.GetType().GetProperties();
            }
            catch (Exception ex)
            {
    
                throw ex;
            }
        }
    
        public PropertyInfo GetByParameterName(string ParameterName)
        {
            try
            {
                return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName);
            }
            catch (Exception ex)
            {
    
                throw ex;
            }
        }
    
        public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue)
        {
            try
            {
                obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue);
                return obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 10:32

    Based on @MarcGravell's answer, here's a version that works in Unity C#.

    ObjectsClass foo = this;
    foreach(var prop in foo.GetType().GetProperties()) {
        Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null));
    }
    
    0 讨论(0)
  • 2020-11-21 10:34

    You can use reflection.

    Type typeOfMyObject = myObject.GetType();
    PropertyInfo[] properties =typeOfMyObject.GetProperties();
    
    0 讨论(0)
  • 2020-11-21 10:36
    public List<string> GetPropertiesNameOfClass(object pObject)
    {
        List<string> propertyList = new List<string>();
        if (pObject != null)
        {
            foreach (var prop in pObject.GetType().GetProperties())
            {
                propertyList.Add(prop.Name);
            }
        }
        return propertyList;
    }
    

    This function is for getting list of Class Properties.

    0 讨论(0)
  • 2020-11-21 10:37

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

    public static Dictionary<string, object> DictionaryFromType(object atype)
    {
        if (atype == null) return new Dictionary<string, object>();
        Type t = atype.GetType();
        PropertyInfo[] props = t.GetProperties();
        Dictionary<string, object> dict = new Dictionary<string, object>();
        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<string, object> DictionaryFromType(object atype, 
         Dictionary<string, object[]> 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<string> propNames = new List<string>();
        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.

    0 讨论(0)
  • 2020-11-21 10:39

    Here is improved @lucasjones answer. I included improvements mentioned in comment section after his answer. I hope someone will find this useful.

    public static string[] GetTypePropertyNames(object classObject,  BindingFlags bindingFlags)
    {
        if (classObject == null)
        {
            throw new ArgumentNullException(nameof(classObject));
        }
    
            var type = classObject.GetType();
            var propertyInfos = type.GetProperties(bindingFlags);
    
            return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
     }
    
    0 讨论(0)
提交回复
热议问题