使用反射修剪对象上的所有字符串



假设我有一个简单的模型结构,如下所示,我想修剪嵌套模型(包含FriendRequest(中每个字符串的空白

{
public string id { get; set; }
public string name { get; set; }
}
public class Request
{
public string name{ get; set; }
public string street { get; set; }
public List<string> tags { get; set; }
public Friend friend { get; set; }
public string greeting { get; set; }
public string favoriteFruit { get; set; }
} 

这个实现只处理顶部Request级别的字符串——我也需要能够处理Friend级别(嵌套(的字符串。

private static T TrimWhiteSpaceOnRequest<T>(T obj)
{
if (obj != null) 
{
PropertyInfo[] properties = obj!.GetType().GetProperties();
foreach (PropertyInfo property in properties) {
try
{
if (property.PropertyType == typeof(string)) 
{
var o = property.GetValue(obj, null) ?? "";
string s = (string)o;
property.SetValue(obj, s.Trim());
}
else
{
//handle nested Friend object here

}
}
catch (Exception)
{
log.info("Error converting field " + field.getName());
}
}

}
return obj;
}

我可以在其他层中放入什么来到达嵌套层?

您可以对非字符串属性的值递归调用TrimWhiteSpaceOnRequest

else
{
TrimWhiteSpaceOnRequest(property.GetValue(obj));
}

您可以对任何非string属性的值调用TrimWhiteSpaceOnRequest函数。

if (prop.PropertyType == typeof(string)
{
// Your existing code...
}
else
{
TrimWhiteSpaceOnRequest(property.GetValue(obj));
}

然而,这不会让你一路过关斩将。您还需要处理作为集合的属性,如IEnumerable。例如,如果不是一个Friend实例Request可以有多个Friend实例,该怎么办?

您可以通过检查obj是否可以强制转换为System.Collections.IEnumerable,如果可以的话,对其进行迭代,并在IEnumerable中的每个实例上调用TrimWhiteSpaceOnRequest来处理此问题。

public static void TrimWhiteSpaceOnRequest<T>(this T obj)
{
if (obj != null)
{
System.Collections.IEnumerable objAsEnumerable = obj as System.Collections.IEnumerable;
if (objAsEnumerable != null)
{
foreach (object enumerableObj in objAsEnumerable)
{
if (enumerableObj != null)
{
TrimStringProperties(enumerableObj);
}
}
return;
}
// The rest of your code...
}
}

然而,仍然不会让您达到目的。您还需要处理string的可变集合,例如Request.tags属性。

处理这种情况的一种方法是查看CCD_ 18是否可以转换为CCD_。如果可以的话,通过for循环对其进行迭代,并修剪每个非空字符串。

public static void TrimWhiteSpaceOnRequest<T>(this T obj)
{
if (obj != null)
{
System.Collections.Generic.IList<string> objAsList = obj as System.Collections.Generic.IList<string>;
if (objAsList != null)
{
for (int i = 0; i < objAsList.Count; i++)
{
string listObject = objAsList[i];
if (listObject != null)
{
objAsList[i] = listObject.Trim();
}
}
return;
}
// Check if obj is IEnumerable...
// The rest of your code...
}
}

这应该可以处理您所介绍的Requestclass。但是,当您添加到class中时,或者如果您试图在其他类上使用TrimWhiteSpaceOnRequest,您可能会遇到此处未涵盖的情况。

最新更新