【问题标题】:Get ALL string properties nested within Wrapper class C#获取嵌套在 Wrapper 类 C# 中的所有字符串属性
【发布时间】:2019-08-13 02:35:07
【问题描述】:

我一直在拼命想弄清楚如何动态遍历对象层次结构以查找父类下的所有字符串属性并对这些字符串进行替换。

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

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 或任何其他对象中的所有字符串属性。我想找到父类中的字符串属性“FamilyName”,但我也想找到嵌套类中的所有字符串值。我想找到每个人的 FirstName 和 LastName 的所有字符串以及嵌套在子类中的对象内的任何字符串。

.GetType().GetProperties().Where(prop => prop.PropertyType == typeof(string))

这将使我获得 ParentWrapper 类中的所有字符串属性,但我希望能够动态地深入到所有不同的级别。

希望我的请求是有道理的。

【问题讨论】:

  • 你知道如何用 C# 编写递归方法吗?
  • 是的,@DavidBrowne-Microsoft
  • 然后编写一个递归方法来枚举对象的属性,并且对于每个属性,1) 将其添加到字符串属性列表中 2) 忽略它或 3) 使用属性的值递归调用自身.
  • 你想对string[](字符串数组)成员做什么?
  • 您要查找属性的值,还是要查找字段或属性的MemberInfo?你想如何区分例如FirstNameDad 来自 FirstNameMom?

标签: c# linq system.reflection


【解决方案1】:

我现在不能检查它,但我认为你可以在这里做一些递归,比如:

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);
            }
        }
    }

【讨论】:

  • 你需要传递一个对象实例,而不是一个类型。
  • 非常感谢@DavidBrowne-Microsoft 和 F3cro。你很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
相关资源
最近更新 更多