C# 对象遍历 string类型 null转空字符串和去前后空格
using System; using System.Collections.Generic; namespace OA.Common.Extensions { /// <summary> /// 对象string类型 null转空字符串和去前后空格 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static T ObjectNullToString<T>(this T obj) { foreach (System.Reflection.PropertyInfo info in obj.GetType().GetProperties()) { if (info.PropertyType == typeof(System.String)) { var value = obj.GetType().GetProperty(info.Name).GetValue(obj); if (value == null) { obj.GetType().GetProperty(info.Name).SetValue(obj, ""); } else { obj.GetType().GetProperty(info.Name).SetValue(obj, value.ToString().Trim()); } } } return obj; } }
//(obj)对象string类型 null转空字符串和去前后空格
obj.ObjectNullToString<类名>();