本文介绍了序列化对象的自定义字符串格式用于输出文件的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正要实施以产生一个Excel友好的格式写入到输出文件,这将在后面捡起并处理特定的业务类的ToString()的覆盖。下面是该数据应该是这样的:

I was just about to implement an override of ToString() on a particular business class in order to produce an Excel-friendly format to write to an output file, which will be picked up later and processed. Here's what the data is supposed to look like:

5555555 "LASTN SR, FIRSTN"	5555555555	13956 STREET RD 	TOWNSVILLE	MI	48890	25.88	01-003-06-0934

这没什么大不了的,我只是做一个格式字符串和重写的ToString(),但将改变的ToString()的行为为我决定序列化这种方式,使得实施的ToString()的任何对象所有衣衫褴褛整个库。

It's no big deal for me to just make a format string and override ToString(), but that will change the behavior of ToString() for any objects I decide to serialize this way, making the implementation of ToString() all ragged across the library.

现在,我已经读了有关,而一个类实现这听起来像一个好主意,但我还是有点困惑,所有这种逻辑应该驻留以及如何建立格式化类。

Now, I've been reading up on IFormatProvider, and a class implementing it sounds like a good idea, but I'm still a little confused about where all this logic should reside and how to build the formatter class.

做什么,当你需要做一个CSV,制表符分隔或其他一些非XML任意字符串出对象的,你们怎么办?

What do you guys do when you need to make a CSV, tab-delimited or some other non-XML arbitrary string out of an object?

推荐答案

下面是从对象列表创建CSV,使用反射一种通用的方式:

Here is a generic fashion for creating CSV from a list of objects, using reflection:

    public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
    {
        Type t = typeof(T);
        FieldInfo[] fields = t.GetFields();

        string header = String.Join(separator, fields.Select(f => f.Name).ToArray());

        StringBuilder csvdata = new StringBuilder();
        csvdata.AppendLine(header);

        foreach (var o in objectlist) 
            csvdata.AppendLine(ToCsvFields(separator, fields, o));

        return csvdata.ToString();
    }

    public static string ToCsvFields(string separator, FieldInfo[] fields, object o)
    {
        StringBuilder linie = new StringBuilder();

        foreach (var f in fields)
        {
            if (linie.Length > 0)
                linie.Append(separator);

            var x = f.GetValue(o);

            if (x != null)
                linie.Append(x.ToString());
        }

        return linie.ToString();
    }

许多变化可以由,如在ToCsv直接写出到文件中(),或具有一个IEnumerable和产量语句取代的StringBuilder

Many variations can be made, such as writing out directly to a file in ToCsv(), or replacing the StringBuilder with an IEnumerable and yield statements.

这篇关于序列化对象的自定义字符串格式用于输出文件的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 01:26