首页 > 解决方案 > 更改对象中每个字符串属性的值

问题描述

我有一个包含许多子对象的对象,每个子对象都有不同数量的字符串属性。

我想编写一个方法,允许我输入一个父对象,该对象将遍历每个子对象中的每个字符串属性,并从属性内容中修剪空白。

对于可视化:

public class Parent
{
    Child1 child1 { get; set;}
    Child2 child2 { get; set;}
    Child3 child3 { get; set;}
}

public class Child1 (Child2 and Child3 classes are similar)
{
    string X { get; set; }
    string Y { get; set; }
    string Z { get; set; }
}

我有以下代码,它在父类中创建一个属性列表,然后遍历每个属性并找到字符串的子属性,然后对它们进行操作。但是由于某种原因,这似乎对属性的值没有任何影响。

private Parent ReduceWhitespaceAndTrimInstruction(Parent p)
{
    var parentProperties = p.GetType().GetProperties();

    foreach(var properties in parentProperties)
    {
        var stringProperties = p.GetType().GetProperties()
            .Where(p => p.PropertyType == typeof(string));

        foreach(var stringProperty in stringProperties)
        {
            string currentValue = (string)stringProperty.GetValue(instruction, null);

            stringProperty.SetValue(p, currentValue.ToString().Trim(), null);
        }
    }
    return instruction;
}

编辑:忘了提。问题似乎来自内部foreach,外部 foreach 查找每个属性,但查找仅是字符串的属性似乎无法正常工作。

编辑:更新方法

private Parent ReduceAndTrim(Parent parent)
        {
            var parentProperties = parent.GetType().GetProperties();

            foreach (var property in parentProperties)
            {
                var child = property.GetValue(parent);
                var stringProperties = child.GetType().GetProperties()
                    .Where(x => x.PropertyType == typeof(string));

                foreach (var stringProperty in stringProperties)
                {
                    string currentValue = (string) stringProperty.GetValue(child, null);
                    stringProperty.SetValue(child, currentValue.ToString().Trim(), null);
                }
            }

            return parent;
        }

标签: c#

解决方案


您的stringProperties枚举不包含任何项目,因为您要求Parent类型为您提供类型的所有属性string- 没有。

var stringProperties = p.GetType().GetProperties()
    .Where(p => p.PropertyType == typeof(string));

注意p是类型Parent,所以p.GetType()产量typeof(Parent)

您需要获取's 实例Child的每个属性值(每个实例) :Parent

var parentProperties = p.GetType().GetProperties();

foreach (var property in parentProperties)
{    
    var child = property.GetValue(p);
    var stringProperties = child.GetType().GetProperties()
        .Where(p => p.PropertyType == typeof(string));

    // etc
}

推荐阅读