C# 获取嵌套在包装类C中的所有字符串属性

C# 获取嵌套在包装类C中的所有字符串属性,c#,linq,system.reflection,C#,Linq,System.reflection,我一直在绞尽脑汁想弄清楚如何动态遍历对象层次结构,找到父类下的所有字符串属性,并替换这些字符串 假设我有一个具有一些属性的父包装器类。像这样 public class ParentWrapper { public Person Mom { get; set; } public Person Dad { get; set; } public IEnumerable<Person> Children { get; set; } public Person

我一直在绞尽脑汁想弄清楚如何动态遍历对象层次结构,找到父类下的所有字符串属性,并替换这些字符串

假设我有一个具有一些属性的父包装器类。像这样

public class ParentWrapper
{
    public Person Mom { get; set; }
    public Person Dad { get; set; }
    public IEnumerable<Person> Children { get; set; }
    public Person FavoritePerson { get; set; }
    public string FamilyName { get; set; }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
这将获得ParentWrapper类中的所有字符串属性,但我希望能够动态深入到所有不同的级别


希望我的要求有意义

我现在无法检查,但我想你可以在这里做一些递归操作,比如:

private static void ReadPropertiesRecursive(Type type)
    {
        foreach (PropertyInfo property in type.GetProperties())
        {
            if (property.PropertyType == typeof(string))
            {
                var FamilyName = property.GetValue(property))// something like this
                //do what u want with searched values
            }
            if (property.PropertyType.IsClass)
            {
                ReadPropertiesRecursive(property.PropertyType);
            }
        }
    }

你知道如何用C写递归方法吗?是的,@DavidBrowne microsoft然后写一个递归方法来枚举对象的属性,对于每个属性,1将其添加到字符串属性列表中,2忽略它,或3使用属性值递归调用它自己。你想对字符串[]做什么字符串数组成员?是要查找属性值,还是要查找字段或属性的MemberInfo?您想如何区分爸爸的名字和妈妈的名字?您需要传递一个对象实例,而不是类型。非常感谢,@DavidBrowne Microsoft和F3cro。你帮了大忙。
private static void ReadPropertiesRecursive(Type type)
    {
        foreach (PropertyInfo property in type.GetProperties())
        {
            if (property.PropertyType == typeof(string))
            {
                var FamilyName = property.GetValue(property))// something like this
                //do what u want with searched values
            }
            if (property.PropertyType.IsClass)
            {
                ReadPropertiesRecursive(property.PropertyType);
            }
        }
    }