Data contract serialization for IList<T>
I have the following code in which I'm trying to serialize a list to a file
public static void Serialize<T>(this IList<T> list, string f开发者_如何学GoileName)
{
try
{
var ds = new DataContractSerializer(typeof(T));
using (Stream s = File.Create(fileName))
ds.WriteObject(s, list);
}
catch (Exception e)
{
_logger.Error(e);
throw;
}
}
and I'm getting the exception:
Type 'System.Collections.Generic.List`1[[MyClass, MyNameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOf*MyClass*:http://schemas.datacontract.org/2004/07/MyNameSpace' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
[KnownType(typeof(MyClass))]
[DataContract]
public class MyClass
{
#region Properties
[DataMember]
public string Foo{ set; get; }
[DataMember]
public string Bar{ set; get; }
}
Any ideas?
There is no inheritance.
What has happened is that the serializer is expecting an instance of T, not a list of T, so you want your method to be like so:
public static void Serialize<T>(this IList<T> list, string fileName)
{
try
{
var ds = new DataContractSerializer(list.GetType());
using (Stream s = File.Create(fileName))
ds.WriteObject(s, list);
}
catch (Exception e)
{
_logger.Error(e);
throw;
}
}
As suggested, the serializer should be for the list, not the type of items.
Additionally, [KnownType(typeof(MyClass))]
should take a class inheriting from MyClass in parameter, not MyClass itself.
try this instead:
var ds = new DataContractSerializer(typeof(T[]));
精彩评论