Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Implementing ISerializationSurrogate
Message
De
04/03/2009 06:59:06
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Titre:
Implementing ISerializationSurrogate
Divers
Thread ID:
01385429
Message ID:
01385429
Vues:
318
Hi,

I posted this in the WPF category and got no replies - but it's not really a WPF specific thing so I'm trying again here:

I think I'm missing something simple. Here's a simple class:
public class ShapeCanvas4 : Canvas
{
    public string SomeField;
    public ShapeCanvas4()
    {
    }
}
And here's an equally simple Serialization surrogate:
public class ShapeCanvas4Surrogate : ISerializationSurrogate
  {
   public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
   {
        ShapeCanvas4 sc3 = (ShapeCanvas4)obj;
        info.AddValue("SomeField", sc3.SomeField);
        info.AddValue("Name", sc3.Name);
   }
    public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
        ShapeCanvas4 sc4 = (ShapeCanvas4)obj;
        sc4.SomeField =info.GetString("SomeField");
        string s = info.GetString("Name");
        sc4.Name = s;
        return sc4;
    }
}
I instantiate an instance of ShapeCanvas4, set SomeField to something, register the surrogate with a BinaryFormatter and serialize it. When I deserialize I get an InvalidOperationException on the line "sc4.Name = s;" Message is "Current local value enumeration is outdated because one or more local values have been set since its creation.". Anyone know why this doesn't work ?

Update: For completeness here's the test code:
ShapeCanvas4 sc4 = new ShapeCanvas4();
sc4.SomeField = "Fred";

MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();

SurrogateSelector ss = new SurrogateSelector();
ShapeCanvas4Surrogate sc4Surrogate = new ShapeCanvas4Surrogate();
ss.AddSurrogate(typeof(ShapeCanvas4), new StreamingContext(StreamingContextStates.All), sc4Surrogate);
formatter.SurrogateSelector = ss;

formatter.Serialize(fs, sc4);
fs.Position = 0;
ShapeCanvas4 newSC4 = (ShapeCanvas4)formatter.Deserialize(fs);
(Guess I should have posted this in a general .NET category since it's not WPF specific)
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform