序列化静态类? [英] Serialize a Static Class?

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

问题描述

如果我们序列化一个静态类,会发生什么?可如果我们把它序列化的静态类的多个实例被创建?

What happens if we serialize a static class? Can more than one instance of the static class be created if we serialize it?

[Serializable]
public static class MyClass
{
    public static MyClass()
    {

    }

    public static bool IsTrue()
    {
       return true;
    }
}

假设我XMLSERIALIZE对象到一个XML文件,并在稍后的时间我去序列回对象。另一个副本存在于存储器(当有人为instintiated首次静态CALSS创建)。请问,会有的物体的两个副本?如果是的话,我们可以停止?它是否适用于随后的单例模式的类?

Suppose I XmlSerialize the object to a XML file, and at a later time I de-serialize back to a object. Another copy exists in the memory (created when somone instintiated the static calss for the first time). Will, there be two copy of the of the object? If yes, can we stop that? Does it apply to any class which follows the singleton pattern?

推荐答案

有永远的任何的静态类的实例:它们都是抽象的,在IL密封的,所以CLR将prevent创建任何实例。因此,有什么可序列化。静态字段永远不会序列化,这是国家唯一的那种静态类可以有。

There are never any instances of static classes: they are both abstract and sealed in the IL, so the CLR will prevent any instances being created. Therefore there is nothing to serialize. Static fields are never serialized, and that's the only sort of state that a static class can have.

您关于XML序列化的问题是没有意义的,因为没有人能够创建静态类的实例开始。

Your question about XML serialization makes no sense, as no-one can ever have created an instance of the static class to start with.

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

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