问题
I'm writing a generic filter class that will be primarily used to filter persons from a population. I'm trying to serialize the filter class, but at runtime I get an SerializationException:
System.Runtime.Serialization.SerializationException : Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' 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.
My filter class looks like this:
[DataContract(Name = "Filter", Namespace = "")]
public class Filter<T>
{
/// <summary>
/// Default constructor, needed by serializers.
/// </summary>
public Filter()
{
Name = "New filter";
Predicates = new List<Predicate<T>>();
}
/// <summary>
/// ctor. Takes a list of predicates for type T
/// to filter with.
/// </summary>
public Filter(string name, IEnumerable<Predicate<T>> predicates)
{
Name = name;
Predicates = predicates.ToList();
}
/// <summary>
/// Name of the filter.
/// </summary>
[DataMember(Order = 0)]
public string Name
{
get;
set;
}
[DataMember(Order = 1)]
public List<Predicate<T>> Predicates
{
get;
set;
}
/// <summary>
/// Filters sequence of type T.
/// </summary>
public IEnumerable<T> ApplyFilter(IEnumerable<T> input)
{
var result = new List<T>(input);
return Predicates.Aggregate(result, (current, predicate) => current.FindAll(predicate));
}
}
When serializing the filter class, I get the above exception. If I don't mark the Predicate as a DataMember, then it works. But obviously I want to serialize that property as well.
I've been at this for a couple of hours now, and I can't figure it out. Any helps would be really appreciated!
回答1:
DataContractSerializer
is not intended for serializing delegates; a multi-cast delegate is a set of arbitrary target objects and methods; this is not a well-defined data-oriented contract. DataContractSerializer
is intended for data.
Either serialize some form of expression as a string (or some simple tree), or use a different serializer.
来源:https://stackoverflow.com/questions/11612737/datacontract-serializationexception-when-using-list-of-predicates