Using PropertyInfo to find out the property type

前端 未结 2 876
無奈伤痛
無奈伤痛 2020-11-30 03:01

I want to dynamically parse an object tree to do some custom validation. The validation is not important as such, but I want to understand the PropertyInfo class better.

相关标签:
2条回答
  • 2020-11-30 03:26

    I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

    public static bool IsStringType(object data)
        {
            return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
        }
    
    0 讨论(0)
  • 2020-11-30 03:31

    Use PropertyInfo.PropertyType to get the type of the property.

    public bool ValidateData(object data)
    {
        foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(string))
            {
                string value = propertyInfo.GetValue(data, null);
    
                if value is not OK
                {
                    return false;
                }
            }
        }            
    
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题