更新时间:2023-09-05 21:32:52
基于您在问题中显示的类,您将需要递归调用来迭代对象属性.可以重复使用的东西怎么样:
Based on classes you showed in your question, you would need a recursive call to iterate your object properties. How about something you can reuse:
object GetValueFromClassProperty(string propname, object instance)
{
var type = instance.GetType();
foreach (var property in type.GetProperties())
{
var value = property.GetValue(instance, null);
if (property.PropertyType.FullName != "System.String"
&& !property.PropertyType.IsPrimitive)
{
return GetValueFromClassProperty(propname, value);
}
else if (property.Name == propname)
{
return value;
}
}
// if you reach this point then the property does not exists
return null;
}
propname
是您要搜索的属性.您可以这样使用:
propname
is the property you are searching for. You can use is like this:
var val = GetValueFromClassProperty("Shape", myCar );