Using BinaryFormatter in C#, I am trying to deserialize objects from a class that includes a delegate property.
After adding a member on the class referred by the delegate the deserialization breaks. See example below.
I would need the deserialization to work even if I completely ignore the problematic delegate property. For example, if the delegate property is always deserialized to null the issue would be solved. I was not able to solve it by marking the property as [NonSerialized] or changing it into a field.
The following would describe the serialized objects that I am trying to deserialize.
public class mySerializedClass
{
public string thisIsOK1 {get; set;}
public string thisIsOK2 {get; set;}
public Func<myModelClass,bool> thisIsTheIssue {get; set;}
}
[Serializable]
public class myModelClass
{
// The issue happened after adding a new method to this class
public static bool testMethod(mySerializedClass obj)
{
// do stuff
return true
}
}
As example of a serialized instance:
new mySerializedClass()
{
thisIsOK1 = "a";
thisIsOK2 = "b";
thisIsTheIssue = (o) => myModelClass.testMethod(o);
}
A valid solution would be to always serialize/deserialize the "thisIsTheIssue" property to null.
As additional information, the Exception Message is:
Cannot get the member ' get_theNameOfMyDelegate b__19_0'.
And the Exception's StackTrace is:
at System.Reflection.MemberInfoSerializationHolder.GetRealObject(StreamingContext context) at System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.DoFixups()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream) at ...the place in my code where I deserialize...