R
Roman
Hi there,
I was trying to serialize an object with a List<Interface> as
property. If I do this i get an exception. when I add an extra proerty
with type object[] to my class and mark the original property with
[XmlIgnore] it works.
Is there a bettert way to do this without adding this property?
Thanks in advance
Roman
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
namespace SerializeTest
{
public class Program
{
static void Main(string[] args)
{
// Create objects
MainClass cm = new MainClass();
cm.TestList.Add(new Test1());
// Try to serialize MainClass
XmlTextWriter writer = new XmlTextWriter(Console.Out);
XmlSerializer ser = new XmlSerializer(typeof(MainClass), new Type
[]{typeof(Test1)});
ser.Serialize(writer, cm);
Console.ReadLine();
}
}
[Serializable]
public class MainClass
{
private List<ITest> _test = new List<ITest>();
public object[] TestListO
{
get
{
return (object[])_test.ToArray();
}
set
{
foreach (object o in value)
{
if (o is ITest
&& !_test.Contains((ITest)o))
{
_test.Add((ITest)o);
}
}
}
}
[XmlIgnore]
public List<ITest> TestList
{
get { return _test; }
set { _test = value; }
}
}
[Serializable]
public class Test1 : ITest
{
#region ITest Members
public void Test()
{
Console.WriteLine(this.GetType().Name);
}
#endregion
}
public interface ITest
{
void Test();
}
}
I was trying to serialize an object with a List<Interface> as
property. If I do this i get an exception. when I add an extra proerty
with type object[] to my class and mark the original property with
[XmlIgnore] it works.
Is there a bettert way to do this without adding this property?
Thanks in advance
Roman
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
namespace SerializeTest
{
public class Program
{
static void Main(string[] args)
{
// Create objects
MainClass cm = new MainClass();
cm.TestList.Add(new Test1());
// Try to serialize MainClass
XmlTextWriter writer = new XmlTextWriter(Console.Out);
XmlSerializer ser = new XmlSerializer(typeof(MainClass), new Type
[]{typeof(Test1)});
ser.Serialize(writer, cm);
Console.ReadLine();
}
}
[Serializable]
public class MainClass
{
private List<ITest> _test = new List<ITest>();
public object[] TestListO
{
get
{
return (object[])_test.ToArray();
}
set
{
foreach (object o in value)
{
if (o is ITest
&& !_test.Contains((ITest)o))
{
_test.Add((ITest)o);
}
}
}
}
[XmlIgnore]
public List<ITest> TestList
{
get { return _test; }
set { _test = value; }
}
}
[Serializable]
public class Test1 : ITest
{
#region ITest Members
public void Test()
{
Console.WriteLine(this.GetType().Name);
}
#endregion
}
public interface ITest
{
void Test();
}
}