【发布时间】:2019-05-13 18:34:51
【问题描述】:
我有一个包含许多子对象的对象,每个子对象都有不同数量的字符串属性。
我想编写一个方法,允许我输入单个父对象,该对象将遍历每个子对象中的每个字符串属性,并从属性内容中修剪空白。
可视化:
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;
}
【问题讨论】:
-
在
Where语句中,您不想在那里搜索Child1类型的对象吗? -
正确的是,我将如何遍历在父对象中找到的每个子对象的属性?
-
我认为错误是你在那里使用
p,但你想要var stringProperties = properties .GetType().Get..... -
你为什么不给子对象一个函数,它会给你一个他们所有字符串的列表,所以父对象会实现一个函数来连接它所有子对象的列表。 (或者只是有一个子列表,每个子都有一个子列表?)
-
@JohnnyMopp,
properties.GetType()将提供typeof(PropertyInfo)而这不是 OP 想要的。
标签: c#