我怎么能写所有的值(属性)将在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());