利用反射转换对象list到csv
扒自一工程。。可以学习一下.net中反射的简单用法 /// <summary> /// Take object List as input and export to csv which will be prompt save as dialog /// </summary> /// <typeparam name="T"> Type of object</typeparam> /// <param name="listToExport"> Object list to export</param> /// <param name="seperateChar"> character to use as scv separator</param> public static string ExportListToCSV<T>( List<T> listToExport, string seperateChar) { Int32 success = 0; StringBuilder export = new StringBuilder(); try { string seperator = "" ; StringBuilder builder = new StringBuilder(); //获取表头的 PropertyInfo[] fieldInfo = listToExport[0].GetType().GetProperties(); foreach (PropertyInfo col in fieldInfo) { if (!col.PropertyType.FullName.Equals("System.Data.EntityKey") && !col.PropertyType.FullName.Equals("System.Data.EntityState" )) { builder.Append(seperator).Append(col.Name); seperator = seperateChar; } } export.AppendLine(builder.ToString()); foreach (T dataItem in listToExport) { PropertyInfo[] allProperties = dataItem.GetType().GetProperties(); seperator = ""; StringBuilder builderTmp = new StringBuilder(); //真正求数据域的 foreach (PropertyInfo thisProperty in allProperties) { if (!thisProperty.PropertyType.FullName.Equals("System.Data.EntityKey") && !thisProperty.PropertyType.FullName.Equals("System.Data.EntityState" )) { object value = thisProperty.GetValue(dataItem, null); String propetyValue = (value == null ? String.Empty : value.ToString()); builderTmp.Append(seperator).Append(propetyValue); seperator = seperateChar; } } ++success; export.AppendLine(builderTmp.ToString()); } } catch (Exception ex) { throw ex; } return export.ToString(); } if (!thisProperty.PropertyType.FullName.Equals("System.Data.EntityKey") && !thisProperty.PropertyType.FullName.Equals("System.Data.EntityState")) ...