使用PropertyInfo查找属性类型

pet*_*ter 103 .net c# reflection

我想动态解析一个对象树来做一些自定义验证.验证并不重要,但我想更好地理解PropertyInfo类.

我会做这样的事情,

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;
}
Run Code Online (Sandbox Code Playgroud)

我现在关心的唯一部分是'如果属性是字符串'.如何从PropertyInfo对象中找出它的类型.

我将不得不处理基本的东西,如字符串,整数,双打.但我也必须处理对象,如果是这样,我将需要在对象树中进一步向下遍历这些对象以验证其中的基本数据,它们也将具有字符串等.

谢谢.

Igo*_*aka 197

使用PropertyInfo.PropertyType来获得属性的类型.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @peter是的,`string`和`String`是相等的.`string`是`String`的别名. (4认同)
  • 好的,写了一些单元测试,它是一种享受.它确实对待字符串和字符串相同.我期待,但只是想确定. (3认同)
  • 如何查找不是 String 也不是 int 而是自定义类的属性的类型?例如公共类A objA; (2认同)