在.NET对象的自定义序列化 [英] Custom serialization of an object in .NET

查看:220
本文介绍了在.NET对象的自定义序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求的对象列表序列化到一个平面文件。该电话将是这样的:

I have a requirement to serialize a list of objects to a flat file. The calls will be something like:

class MyObject
{
    public int x;
    public int y;
    public string a;
    public string b;
}

当我序列化这个对象,记录应该写在一个ASCII EN codeD平面文件。现在,场X的长度应为10个字符(右对齐),场ý应为20个字符(右对齐),fiels一个应为40(左对齐)和字段B应为100个字符(左对齐)。 如何能够做到这样的事情。

When I serialize this object, a record should be written in a ascii encoded flat file. Now, the length of field x should be 10 characters (right aligned), field y should be 20 characters (right aligned), fiels a should be 40 (left aligned) and field b should be 100 characters (left aligned). How can I achieve such a thing.

一个序列化对象应该是这样的:

A serialized object should look like :

        25                   8                                     akjsrj                                                                                          jug

我在想,可能是我可以将自定义属性,属性的字段,可以在运行时决定如何去外地序列化。

I was thinking that may be I can apply custom attributes attributes to the fields and can decide at runtime how to serialize the field..

推荐答案

下面是使用老式反射和自定义属性的解决方案。它只会序列化/反序列化每​​个文件一个项目,但你可以很容易地添加对每个文件的多个项目。

Here is a solution that uses plain old reflection and a custom attribute. It will only serialize/deserialize one item per file, but you could easily add support for multiple items per file.

// Attribute making it possible
public class FlatFileAttribute : Attribute
{
    public int Position { get; set; }
    public int Length { get; set; }
    public Padding Padding { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="FlatFileAttribute"/> class.
    /// </summary>
    /// <param name="position">Each item needs to be ordered so that 
    /// serialization/deserilization works even if the properties 
    /// are reordered in the class.</param>
    /// <param name="length">Total width in the text file</param>
    /// <param name="padding">How to do the padding</param>
    public FlatFileAttribute(int position, int length, Padding padding)
    {
        Position = position;
        Length = length;
        Padding = padding;
    }
}

public enum Padding
{
    Left,
    Right
}


/// <summary>
/// Serializer making the actual work
/// </summary>
public class Serializer
{
    private static IEnumerable<PropertyInfo> GetProperties(Type type)
    {
        var attributeType = typeof(FlatFileAttribute);

        return type
            .GetProperties()
            .Where(prop => prop.GetCustomAttributes(attributeType, false).Any())
            .OrderBy(
                prop =>
                ((FlatFileAttribute)prop.GetCustomAttributes(attributeType, false).First()).
                    Position);
    }
    public static void Serialize(object obj, Stream target)
    {
        var properties = GetProperties(obj.GetType());

        using (var writer = new StreamWriter(target))
        {
            var attributeType = typeof(FlatFileAttribute);
            foreach (var propertyInfo in properties)
            {
                var value = propertyInfo.GetValue(obj, null).ToString();
                var attr = (FlatFileAttribute)propertyInfo.GetCustomAttributes(attributeType, false).First();
                value = attr.Padding == Padding.Left ? value.PadLeft(attr.Length) : value.PadRight(attr.Length);
                writer.Write(value);
            }
            writer.WriteLine();
        }
    }

    public static T Deserialize<T>(Stream source) where T : class, new()
    {
        var properties = GetProperties(typeof(T));
        var obj = new T();
        using (var reader = new StreamReader(source))
        {
            var attributeType = typeof(FlatFileAttribute);
            foreach (var propertyInfo in properties)
            {
                var attr = (FlatFileAttribute)propertyInfo.GetCustomAttributes(attributeType, false).First();
                var buffer = new char[attr.Length];
                reader.Read(buffer, 0, buffer.Length);
                var value = new string(buffer).Trim();

                if (propertyInfo.PropertyType != typeof(string))
                    propertyInfo.SetValue(obj, Convert.ChangeType(value, propertyInfo.PropertyType), null);
                else
                    propertyInfo.SetValue(obj, value.Trim(), null);
            }
        }
        return obj;
    }

}

和一个小的演示:

// Sample class using the attributes
public class MyObject
{
    // First field in the file, total width of 5 chars, pad left
    [FlatFile(1, 5, Padding.Left)]
    public int Age { get; set; }

    // Second field in the file, total width of 40 chars, pad right
    [FlatFile(2, 40, Padding.Right)]
    public string Name { get; set; }
}

private static void Main(string[] args)
{
    // Serialize an object
    using (var stream = File.OpenWrite("C:\\temp.dat"))
    {
        var obj = new MyObject { Age = 10, Name = "Sven" };
        Serializer.Serialize(obj, stream);
    }

    // Deserialzie it from the file
    MyObject readFromFile = null;
    using (var stream = File.OpenRead("C:\\temp.dat"))
    {
        readFromFile = Serializer.Deserialize<MyObject>(stream);
    }

}

这篇关于在.NET对象的自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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