代码改变世界

C# 并行 反射 去掉实体属性多余空格

2013-11-06 10:52  Eric.Hu  阅读(644)  评论(0编辑  收藏  举报

 

    有时会遇到很多不合理的数据附件到实体后有大量空格需要处理,这里提供一个方法,通过并行反射的方式高效清理空格。

 

Code:

  1. //清除字符串空格
  2. public static object TrimString(object obj)
  3. {
  4.     try
  5.     {
  6.         Type t = obj.GetType();
  7.         PropertyInfo[] props = t.GetProperties();
  8.  
  9.         Parallel.ForEach(props, p =>
  10.         {
  11.             if (p.PropertyType.Name == "String")
  12.             {
  13.                 var tmp = (string)p.GetValue(obj, null);
  14.                 p.SetValue(obj, tmp.Trim(), null);
  15.             }
  16.         });
  17.  
  18.         return obj;
  19.     }
  20.     catch
  21.     {
  22.         return obj;
  23.     }
  24. }