C# - 从子类中获取属性值

ini*_*iki 8 c# reflection

我在运行时使用C#中的反射从类对象访问属性值.

    public bool GetValue(string fieldName, out object fieldValue)
    {
        // Get type of current record
        Type curentRecordType = _currentObject.GetType();
        PropertyInfo property = curentRecordType.GetProperty(fieldName);

        if (property != null)
        {
            fieldValue = property.GetValue(_currentObject, null).ToString();
            return true;
        }
        else
        {
            fieldValue = null;
            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我将Property Name作为参数:fieldName传递给此方法.现在,我需要在运行时从上面的类的子对象访问属性值.
那里的任何人都可以指导我如何访问子对象属性值?

Gab*_*abe 8

由于您希望能够在任意嵌套的子对象上查找对象,因此您需要一个可以递归调用的函数.这很复杂,因为您可能有孩子会回顾他们的父母,因此您需要跟踪您在搜索中看到过的对象.

static bool GetValue(object currentObject, string propName, out object value)
{
    // call helper function that keeps track of which objects we've seen before
    return GetValue(currentObject, propName, out value, new HashSet<object>());
}

static bool GetValue(object currentObject, string propName, out object value,
                     HashSet<object> searchedObjects)
{
    PropertyInfo propInfo = currentObject.GetType().GetProperty(propName);
    if (propInfo != null)
    {
        value = propInfo.GetValue(currentObject, null);
        return true;
    }
    // search child properties
    foreach (PropertyInfo propInfo2 in currentObject.GetType().GetProperties())
    {   // ignore indexed properties
        if (propInfo2.GetIndexParameters().Length == 0)
        {
            object newObject = propInfo2.GetValue(currentObject, null);
            if (newObject != null && searchedObjects.Add(newObject) &&
                GetValue(newObject, propName, out value, searchedObjects))
                return true;
        }
    }
    // property not found here
    value = null;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

如果您知道您的属性所在的子对象,您可以将路径传递给它,如下所示:

public bool GetValue(string pathName, out object fieldValue) 
{ 
    object currentObject = _currentObject;
    string[] fieldNames = pathName.Split(".");

    foreach (string fieldName in fieldNames)
    {
        // Get type of current record 
        Type curentRecordType = currentObject.GetType(); 
        PropertyInfo property = curentRecordType.GetProperty(fieldName); 

        if (property != null) 
        { 
            currentObject = property.GetValue(currentObject, null).ToString(); 
        } 
        else 
        { 
            fieldValue = null; 
            return false; 
        } 
    }
    fieldValue = currentObject;
    return true; 
} 
Run Code Online (Sandbox Code Playgroud)

而不是像GetValue("foo", out val)你一样称呼它GetValue("foo.bar", out val).