简体   繁体   English

序列化继承:如果基类未标记为[Serializable],会引发异常吗?

[英]Serialization inheritance: Will an exception be thrown if the base class isn't marked [Serializable]?

Taking a practice exam the exam said I got this one wrong. 参加实践考试,考试说我错了。 The answer marked in Yellow is the supposed correct answer. 黄色标记的答案是正确的答案。

In the following quote, the part marked in bold I think is wrong: "The Serializable attribute is not inherited by the derived classes, so if you only mark the Encyclopedia class with the Serializable attribute, the runtime will throw an exception when trying to serialize the Name field ". 在下面的引用中,我认为用粗体标出的部分是错误的:“ Serializable属性未由派生类继承,因此,如果仅将Encyclopedia类标记为Serializable属性, 则在尝试进行序列化时运行时将引发异常“名称”字段

在此处输入图片说明

I actually created a sample project with an Animal class and a Cat class that derives from it. 实际上,我创建了一个带有Animal类和从其派生的Cat类的示例项目。 I marked the Cat class [Serializable] and the Animal class is not. 我将Cat类标记为[Serializable] ,而Animal类则没有标记。

I was able to successfully serialize and deserialize the Cat class, including the Animal properties. 我能够成功地序列化和反序列化Cat类,包括Animal属性。

Is this a .NET version issue? 这是.NET版本问题吗? The exam is 70-536, so it's targeting 2.0. 考试是70-536,因此它的目标是2.0。

Yes, the base class also needs to be serializable. 是的,基类也需要可序列化。 Some easy test code: 一些简单的测试代码:

  public class Animal
    {
        public Animal()
        {
            name = "Test";
        }
        public string name { get; set; }
    }

    [Serializable]
    public class Cat : Animal
    {
        public string color {get; set;}
    }


        var acat = new Cat();
        acat.color = "Green";
        Stream stream = File.Open("test.bin", FileMode.Create);
        BinaryFormatter bformatter = new BinaryFormatter();

        bformatter.Serialize(stream, acat);
        stream.Close();

When you try to serialize, you get this error: 当您尝试序列化时,会出现以下错误:

Type 'SerializeTest.Animal' in Assembly 'SerializeTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 程序集“ SerializeTest,版本= 1.0.0.0,区域性=中性,PublicKeyToken =空”中的类型“ SerializeTest.Animal”未标记为可序列化。

edit - I notice that you did the same thing but it worked for you. 编辑-我注意到您做了同样的事情,但是对您有用。 Do you have the code you used? 您有使用的代码吗? This one is in .net 4, but I don't think its changed that much between versions. 这个是在.net 4中,但我认为它在版本之间没有太大变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM