C# 递归过程中PropertyInfo GetValue抛出错误
当我试图在运行时在我的C#程序中检索对象的值时,我得到了“对象不匹配目标类型” 我传递了我的类BrokerInfo的一个对象,它有一个Broker类型的属性,inturn有属性——FirstName和LastName(为了简单起见,所有字符串) 我尝试递归地检查自定义类型并尝试获取它们的值。我可以做一些事情,比如:C# 递归过程中PropertyInfo GetValue抛出错误,c#,reflection,propertyinfo,C#,Reflection,Propertyinfo,当我试图在运行时在我的C#程序中检索对象的值时,我得到了“对象不匹配目标类型” 我传递了我的类BrokerInfo的一个对象,它有一个Broker类型的属性,inturn有属性——FirstName和LastName(为了简单起见,所有字符串) 我尝试递归地检查自定义类型并尝试获取它们的值。我可以做一些事情,比如: - Broker - FirstName - LastName var o = pinfo.GetValue(obj, null); GetMyProperties
- Broker
- FirstName
- LastName
var o = pinfo.GetValue(obj, null);
GetMyProperties(o);
请帮忙
更新:能够在leppie的帮助下解决它:这是修改后的代码
public void GetMyProperties(object obj)
{
foreach(PropertyInfo pinfo in obj.GetType().GetProperties())
{
if(!Helper.IsCustomType(pinfo.PropertyType))
{
string s = pinfo.GetValue(obj, null);
propArray.Add(s);
}
else
{
object o = pinfo.GetValue(obj, null);
GetMyProperties(o);
}
}
}
IsCustom是检查类型是否为custome类型的方法。代码如下:
public static bool IsCustomType(Type type)
{
//Check for premitive, enum and string
if (!type.IsPrimitive && !type.IsEnum && type != typeof(string))
{
return true;
}
return false;
}
为什么要深入研究类型而不是实例 具体而言:
object o = pinfo.PropertyType;
GetMyProperties(o);
它应该看起来像:
- Broker
- FirstName
- LastName
var o = pinfo.GetValue(obj, null);
GetMyProperties(o);
你能发布
助手的代码吗?IsCustomType
?@谢谢leppie,我想我做错了:)我很快就会试试这个。leppie,完美的解决方案。我已经发布了上面的修改代码。虽然现在得到另一个问题,但将分别发布。谢谢