我在對象上編寫了一個擴展方法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;
}
你不是應該叫'((對象) customType.GetValue(obj))。TrimSpaces();',即沒有'.GetType()'? –