使用FormatterServices 类序列化或反序列化

本文介绍了一种在.NET中自定义序列化的方法,通过创建BinarySerializeHelper类来辅助实现ISerializable接口,使得派生类可以正确地进行序列化与反序列化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果放一个[Serializable]标签就可以实现自动序列化,我想我不会神经到自己自定义实现序列化.
项目中遇到的问题,Mark下.

引用下MSDN的话:
FormatterServices 类来正确地序列化或反序列化符合以下条件的对象:基类未实现 ISerializable,但派生类实现了该接口。

改抄了一个MSDN类:

ContractedBlock.gifExpandedBlockStart.gifCode
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Reflection;

namespace ecl.Common.Comm
{
    
/// <summary>
    
/// 自定义序列化类
    
/// 详见: ms-help://MS.MSDNQTR.v90.chs/fxref_mscorlib/html/8596f308-b593-d44a-4f16-420430e21302.htm
    
///  08/9/23 created by solo
    
/// </summary>
    public class BinarySerializeHelper
    {
        
public static void Serialize(object obj, SerializationInfo info, StreamingContext context)
        {
            
// 获取指定类的所有可序列化成员
            Type thisType = obj.GetType();
            MemberInfo[] mi 
= FormatterServices.GetSerializableMembers(thisType, context);

            
// Serialize the base class's fields to the info object.
            for (Int32 i = 0; i < mi.Length; i++)
            {
                
// Skip this field if it is marked NonSerialized.
                if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;

                
// Get the value of this field and add it to the SerializationInfo object.
                info.AddValue(mi[i].Name, ((FieldInfo)mi[i]).GetValue(obj));
            }
        }
        
public static void Deserialize(object obj, SerializationInfo info, StreamingContext context)
        {
            Type thisType 
= obj.GetType();
            MemberInfo[] mi 
= FormatterServices.GetSerializableMembers(thisType, context);

            
// 反序列化对象
            for (Int32 i = 0; i < mi.Length; i++)
            {
                
// For easier coding, treat the member as a FieldInfo object
                FieldInfo fi = (FieldInfo)mi[i];

                
// Skip this field if it is marked NonSerialized.
                if (Attribute.IsDefined(mi[i], typeof(NonSerializedAttribute))) continue;

                
// Get the value of this field from the SerializationInfo object.
                fi.SetValue(obj, info.GetValue(fi.Name, fi.FieldType));
            }
        }
    }
}

然后对于要自定义序列化的玩意Manage这样搞下就OK了.这个Demo也是MSDN的

 

 

ContractedBlock.gifExpandedBlockStart.gifCode
None.gifusing System;
None.gif
using System.IO;
None.gif
using System.Runtime.Serialization;
None.gif
using System.Runtime.Serialization.Formatters;
None.gif
using System.Runtime.Serialization.Formatters.Binary;
None.gif
using System.Reflection;
None.gif
using System.Security.Permissions;
None.gif
using ecl.Common.Comm;
None.gif
None.gif
None.gif
// 基类Person 可序列
None.gif
[Serializable]
None.gif
public class Person
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private String title;
InBlock.gif
InBlock.gif    
public Person(String title)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.title = title;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override String ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("{0}", title);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
// Employee 继承Person并可序列化
None.gif
[Serializable]
None.gif
public class Employee : Person
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private String title;
InBlock.gif
InBlock.gif    
public Employee(String title)
InBlock.gif        : 
base("Person")
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.title = title;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override String ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("{0} -> {1}", title, base.ToString());
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
// Manager 可序列化并继承ISerializable
None.gif
[Serializable]
None.gif
public class Manager : Employee, ISerializable
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
private String title;
InBlock.gif    
private String name;
InBlock.gif
InBlock.gif    
public Manager()
InBlock.gif        : 
base("Employee")
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.title = "Manager";
ExpandedSubBlockEnd.gif    }

InBlock.gif    
public Manager(string _name)
InBlock.gif        : 
base("Employee")
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
this.title = "Manager";
InBlock.gif        
this.name = _name;
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    [SecurityPermission(SecurityAction.Demand, SerializationFormatter 
= true)]
InBlock.gif    
public void GetObjectData(SerializationInfo info, StreamingContext context)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif
InBlock.gif
InBlock.gif        
//序列化对象中你需要的元素
InBlock.gif
        BinarySerializeHelper.Serialize(this, info, context);
InBlock.gif
InBlock.gif        DisplaySerializationInfo(info);
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
private void DisplaySerializationInfo(SerializationInfo info)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        SerializationInfoEnumerator e 
= info.GetEnumerator();
InBlock.gif        Console.WriteLine(
"Values in the SerializationInfo:");
InBlock.gif        
while (e.MoveNext())
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.WriteLine(
"Name={0}, ObjectType={1}, Value={2}", e.Name, e.ObjectType, e.Value);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    [SecurityPermissionAttribute(SecurityAction.Demand, Flags 
= SecurityPermissionFlag.SerializationFormatter)]
InBlock.gif    
protected Manager(SerializationInfo info, StreamingContext context)
InBlock.gif        : 
base(null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
// 反序列化构造对象元素
InBlock.gif
        BinarySerializeHelper.Deserialize(this, info, context);
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public override String ToString()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
return String.Format("{0} -> {1}", title, base.ToString());
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
None.gif
public sealed class App
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Run();
InBlock.gif        Console.ReadLine();
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public static void Run()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
using (Stream stream = new MemoryStream())
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IFormatter formatter 
= new BinaryFormatter();
InBlock.gif            Manager m 
= new Manager("solo");
InBlock.gif            Console.WriteLine(m.ToString());
InBlock.gif            formatter.Serialize(stream, m);
InBlock.gif
InBlock.gif            stream.Position 
= 0;
InBlock.gif            m 
= (Manager)formatter.Deserialize(stream);
InBlock.gif            Console.WriteLine(m.ToString());
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

 

转载于:https://www.cnblogs.com/solo/archive/2008/09/23/1296718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值