A list of interfaces which is implemented by an abstract klass with two subclasses that need to be serialised. I have no idea how to do this since interfaces can not be serialised as I understand it.
My code generates the error message:
Cannot serialize interface ConsoleApplication4.Creature_interface.
..allthough Im not trying to serilize the interfaces themselves.
Which is the right way to deal with a problem like this? Is there any stright
way to deal with this problem or is there some kind of workaround needed?
Code:using System; using System.Collections.Generic; using System.Text; using UtilitiesLibrary; using System.Xml.Serialization; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Cat cat1 = new Cat("Knut", 6); Dog dog1 = new Dog("Bertil", 5); List<Creature_interface> Animallist = new List<Creature_interface>(); Animallist.Add(cat1); Animallist.Add(dog1); UniversalSerializer.XMLSerialize("filename.xml", Animallist); Console.ReadLine(); } } public interface Creature_interface { string Name { get;} int Age { get; } } public abstract class Creature : Creature_interface { string _name; int _age; public Creature(string name, int age ) { _name = name; _age = age; } public Creature() { } public string Name { get { return _name; } set { _name = value; } } public int Age { get { return _age; } set { _age = value; } } public abstract void Speak(); } [Serializable] public class Dog:Creature { public Dog (string _name, int _age): base (_name, _age) { } public Dog { } public override void Speak() { Console.WriteLine("Bark Bark"); } } [Serializable] public class Cat:Creature { public Cat (string _name, int _age): base (_name, _age) { } public Cat { } public override void Speak() { Console.WriteLine("Mjau Mjau"); } } }Thank you for any help.Code:using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace UtilitiesLibrary { public class UniversalSerializer { public static void XMLSerialize<T>(string filename, T objectToSerialize) { XmlSerializer Serializer = new XmlSerializer(typeof(List<Creature_interface>), new Type[] {typeof(Dog), typeof(Cat)}); Stream fStream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None); Serializer.Serialize(fStream, objectToSerialize); fStream.Close(); } //more methods... } }




Reply With Quote