gpt4 book ai didi

c# - 使用反射递归地修剪对象中的空间

转载 作者:行者123 更新时间:2023-11-30 23:29:48 24 4
gpt4 key购买 nike

我正在一个对象上编写一个扩展方法 TrimSpaces,以便它能够递归地修剪空格。我成功地修剪了第一级对象的空间,但是,我无法为子对象做同样的事情。

例如,考虑以下类

public class Employee
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTime HireDate { get; set; }
public Department EmployeeDepartment { get; set; }
}

public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
}

在上面的类中,我目前能够从 Employee 类属性中修剪空格,但我无法修剪 DepartmentName

这是我写的代码

    public static T TrimSpaces<T>(this T obj)
{
var properties = obj.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(prop => prop.PropertyType == typeof(string))
.Where(prop => prop.CanWrite && prop.CanRead);
foreach (var property in properties)
{
var value = (string)property.GetValue(obj, null);
if (value.HasValue())
{
var newValue = (object)value.Trim();
property.SetValue(obj, newValue, null);
}
}


var customTypes =
obj.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(
prop =>
!prop.GetType().IsPrimitive && prop.GetType().IsClass &&
!prop.PropertyType.FullName.StartsWith("System"));

foreach (var customType in customTypes)
{
((object)customType.GetValue(obj).GetType()).TrimSpaces();
}

return obj;
}

最佳答案

当您遍历属性时,您正在调用这一行:

((object)customType.GetValue(obj).GetType()).TrimSpaces(); 

调用 TrimSpaces 将对象类型作为 obj 传递。相反,您应该像这样自行传递对象:

((object)customType.GetValue(obj)).TrimSpaces();

在这种情况下,不需要强制转换为 object,因此您可以这样做:

customType.GetValue(obj).TrimSpaces();

关于c# - 使用反射递归地修剪对象中的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com