How to get the list of properties of a class?

后端 未结 10 1326
陌清茗
陌清茗 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;
            }
        }
    }
    

提交回复
热议问题