Using PropertyInfo to find out the property type

前端 未结 2 896
無奈伤痛
無奈伤痛 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: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;
    }
    

提交回复
热议问题