更改对象中每个字符串属性的值

时间:2018-12-12 15:51:12

标签: c#

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

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

为了可视化:

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

2 个答案:

答案 0 :(得分:1)

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

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

请注意,p的类型为Parent,因此p.GetType()会产生typeof(Parent)

您需要获取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
}

答案 1 :(得分:0)

GetProperties方法仅返回您类型的 public 属性。如果将Parent类的属性更改为以下内容,则应该可以继续前进:

public class Parent
{
    public Child1 Child1 { get; set; }
    public Child2 Child2 { get; set; }
    public Child3 Child3 { get; set; }
}

但是这行代码仍将返回null,因为子类中没有“ parent”属性:

var child = property.GetValue(parent);

我希望它对您有帮助:D

相关问题