且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用字符串作为属性名称从嵌套对象组中找到对象属性值?

更新时间: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 );