对象实体CSV序列化/转换 [英] Object entity to CSV serialization / conversion

查看:184
本文介绍了对象实体CSV序列化/转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能写所有的值(属性)将在C#中的CSV格式化字符串? 例如:

How can I write all values (properties) into an csv formated string in C#? e.g.:

class Person(string firstName, string lastName, int_age);
Person person = new Person("Kevin","Kline",33);

现在我想一个字符串凯文;克莱恩; 33

在换句话说,我想序列化对象为CSV

In other words I want to serialize an object into CSV

推荐答案

通过使用反射,你可以从一个对象获取属性的相关信息。

By using reflection you can retrieve the property infos from an object

foreach (PropertyInfo prp in obj.GetType().GetProperties()) {
   if (prp.CanRead) {
      object value = prp.GetValue(obj, null);
      string s = value == null ? "" : value.ToString();
      string name = prp.Name;
      ...
   }
} 

的GetProperties,方法有一个重载接受的BindingFlags 这让你确定你需要哪一种性质,如私人/公共成员/静态的。

The GetProperties method has an overload accepting BindingFlags which let you determine which kind of property you need, like private/public member/static.

您可以将它们像这样

var properties = type.GetProperties(BindingFlags.Public | 
                                    BindingFlags.NonPublic | 
                                    BindingFlags.Instance);


适用于你的问题,你可以写


Applied to your problem you could write

List<Person> people = ...;
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
var sb = new StringBuilder();

// First line contains field names
foreach (PropertyInfo prp in properties) {
   if (prp.CanRead) {
      sb.Append(prp.Name).Append(';');
   }
}
sb.Length--; // Remove last ";"
sb.AppendLine();

foreach (Person person in people) {
    foreach (PropertyInfo prp in properties) {
       if (prp.CanRead) {
          sb.Append(prp.GetValue(person, null)).Append(';');
       }
    }
    sb.Length--; // Remove last ";"
    sb.AppendLine();
}

File.AppendAllText("C:\Data\Persons.csv", sb.ToString());

这篇关于对象实体CSV序列化/转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆