Singleton类中的序列化问题 [英] Serialization Problem in Singleton class

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

问题描述

你好,

我正在C#中创建具有单例类的应用程序.
当我尝试使用二进制序列化序列化该类时.
它创建1KB大小的文件.

以下是我的代码

Hello,

I am creating an application in C# which is having a singleton class.
When i am trying to serialize that class using binary serialization.
It create the file of 1KB size.

Below is my code

FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
try
{
    // Construct a BinaryFormatter and use it  //to serialize the data to the stream.
     BinaryFormatter formatter = new BinaryFormatter();                
     formatter.Serialize(fs, Obj);
}
catch (SerializationException e)
{
    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
    throw;
}
finally
{
    fs.Close();
}



请告诉我上面代码中的任何问题,或者告诉我如何序列化Singleton类


以下是如何创建单例类的代码



Kindly let me know is the any problem in above code or tell me how to serialize Singleton class


below is the code of how singleton class is created

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


namespace Namespace
{
    [Serializable]

public sealed class Singleton: ISerializable
    {
        private static readonly Singleton Obj = new Singleton ();

        private Singleton() { }

        public static Singleton GetInstance
        {
            get
            {                
                return Obj;
            }
        }

        internal sealed class SingletonSerializationHelper : IObjectReference
        {
            // This object has no fields (although it could).

            // GetRealObject is called after this object is deserialized.
            public Object GetRealObject(StreamingContext context)
            {
                // When deserialiing this object, return a reference to
                // the Singleton object instead.
                return Singleton.Obj;
            }
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {

            info.SetType(typeof(SingletonSerializationHelper));
        }





在Advanced中表示感谢.





Thanks in Advanced.

推荐答案

如果您的单例是静态类,则从原则上讲,以这种方式进行序列化的整个想法就毫无意义.

为了说明这一点,让我们假设您设法以某种方式对其进行了序列化.现在,查看您使用的二进制格式化程序类:
http://msdn. microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28v=vs.100%29.aspx [ http://csharpindepth.com/Articles/General/Singleton.aspx [ http://msdn.microsoft.com/en-us/library/system.serializableattribute%28v = vs.100%29.aspx [
If your singleton is a static class, the whole idea of serialization in this way makes no sense in principle.

To explain it, let''s assume for a minute you managed to serialize it somehow. Now, look at the binary formatter class you use:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter%28v=vs.100%29.aspx[^].

To deserialize, you would need to use the method public Object Deserialize(Stream serializationStream). It returns the object of the type (compile type) System.Object. What would be the runtime type if this object? It supposed to represent the object of the type you have serialized before. But such object cannot exist, because static classes cannot have instances!

You are done, case closed.

Now, what do you want to do? First of all, the singleton implemented as a static class is a bad implementation. Please take a look at something better:
http://csharpindepth.com/Articles/General/Singleton.aspx[^].

Look at this implementation. The class itself is never a static one. If has instance, but the instance is static. It is important that it is private, for proper encapsulation. And the instance can be serialized.



In response to the follow-up question:

The missing thing is the attribute [System.Serializable]. Please see System.SerializableAttribute:
http://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.100%29.aspx[^].

All the types in you object graph should be marked serializable, of course.

—SA


这篇关于Singleton类中的序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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