开发者

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".

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

I actually created a sample project with an Animal class and a Cat class that derives from it. I marked the Cat class [Serializable] and the Animal class is not.

I was able to successfully serialize and deserialize the Cat class, including the Animal properties.

Is this a .NET version issue? The exam is 70-536, so it's targeting 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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜