将对象序列化为自定义字符串格式以在输出文件中使用的最佳实践 [英] Best practices for serializing objects to a custom string format for use in an output file

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

问题描述

我正要在特定业务类上实现 ToString() 的覆盖,以生成 Excel 友好的格式以写入输出文件,稍后将提取并处理该文件.数据应该是这样的:

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.

现在,我一直在阅读 IFormatProvider,以及一个实现它的类听起来是个好主意,但我仍然对所有这些逻辑应该驻留在何处以及如何构建格式化程序类感到有些困惑.

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() 中写入文件,或将 StringBuilder 替换为 IEnumerable 和 yield 语句.

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.

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

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