这个通用的辅助函数遍历对象列表,访问它们的公共属性,并为每个对象输出一个逗号分隔的字符串。
/// <summary>
/// Format the properties as a list of comma delimited values, one object row per.
/// </summary>
/// <typeparam name="T">Type of class contained in the List</typeparam>
/// <param name="list">A list of objects</param>
/// <returns>a list of strings in csv format</returns>
public static List<string> ToCSV<T>(this IEnumerable<T> list)
where T : class
{
var results = new List<string>();
bool firstTime = true;
foreach (var obj in list)
{
// header data
if (firstTime)
{
firstTime = false;
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
line += propertyInfo.Name + ',';
}
}
results.Add(line);
}
else
{
string line = String.Empty;
foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
{
if (propertyInfo.CanRead)
{
object value = propertyInfo.GetValue(obj, null);
if (value.GetType() == typeof(string))
{
line += "\"" + value.ToString() + "\"" + ",";
}
else
{
line += value.ToString() + ",";
}
}
}
results.Add(line);
}
}
return results;
}
被此方法迭代的类之一有一个字符串属性,该属性被截断:
string BusinessItem { get; set; } // "0000", a legitimate business value
有问题的位在这里:
object value = propertyInfo.GetValue(obj, null); // value == 0
如何将属性的值作为字符串而不是 int 获取?