使用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屋!