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)
| 归档时间: |
|
| 查看次数: |
106738 次 |
| 最近记录: |