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;
}
解决方案
您的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
}
推荐阅读
- sublime-text-plugin - Sublime tmPreference 文件:如何拥有多个范围?
- react-native - 后台通知数据获取
- java - 自定义视图 edittext 调用了 setontouchlistener 但不覆盖 performclick
- java - 如何使用 Spring Boot Data JPA 在一对多映射的子实体中设置 parentId
- mysql - 确保 cron 作业不会两次执行相同的作业
- scala - akka 流 CPU 使用率监控
- dart - immutable StatefulWidget 有什么用,和 Flutter 中的 State 一样,但是可以只做一个 mutable StatefulWidget 没有 state
- javascript - 如何更新 jinja 模板中的全局变量?
- c# - 通过 C# 导出到 CSV 文件时将特定的前导零数字列转换为字符串
- angular - 波纹效果指令是全屏而不是仅在元素上