使用 PropertyInfo 找出属性类型 [英] Using PropertyInfo to find out the property type
问题描述
我想动态解析一个对象树来做一些自定义验证.验证本身并不重要,但我想更好地理解 PropertyInfo 类.
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.
我会做这样的事情:
public bool ValidateData(object data)
{
foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
{
if (the property is a string)
{
string value = propertyInfo.GetValue(data, null);
if value is not OK
{
return false;
}
}
}
return true;
}
目前我真正关心的唯一部分是如果属性是字符串".如何从 PropertyInfo 对象中找出它是什么类型?
Really the only part I care about at the moment is 'if the property is a string'. How can I find out from a PropertyInfo object what type it is?
我将不得不处理基本的东西,比如字符串、整数、双精度数.但是我也必须处理对象,如果是这样,我将需要在这些对象内部进一步遍历对象树以验证它们内部的基本数据,它们也将包含字符串等.
I will have to deal with basic stuff like strings, ints, doubles. But I will have to also deal with objects too, and if so I will need to traverse the object tree further down inside those objects to validate the basic data inside them, they will also have strings etc.
推荐答案
使用 PropertyInfo.PropertyType
获取属性的类型.
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;
}
这篇关于使用 PropertyInfo 找出属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!