Come escludere osservatori non serializzabili da un implementatore INotifyPropertyChanged [Serializable]?
-
03-07-2019 - |
Domanda
Ho quasi un centinaio di classi di entità che sembrano così:
[Serializable]
public class SampleEntity : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; FirePropertyChanged("Name"); }
}
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
Nota l'attributo [field: NonSerialized]
su PropertyChanged
. Ciò è necessario poiché alcuni osservatori (nel mio caso - una griglia che mostra le entità per l'edizione) potrebbero non essere serializzabili e l'entità deve essere serializzabile, poiché è fornita, tramite telecomando, da un'applicazione in esecuzione su una macchina separatrice .
Questa soluzione funziona bene per casi banali. Tuttavia, è possibile che alcuni osservatori siano [serializzabili]
e debbano essere preservati. Come dovrei gestirlo?
Soluzioni che sto prendendo in considerazione:
-
completo serializzabile
- la serializzazione personalizzata richiede la scrittura di molto codice, preferirei non farlo - usando
[OnSerializing]
e[OnDeserializing]
per serializzare manualmentePropertyChanged
- ma questi metodi di supporto forniscono soloSerializationContext , che AFAIK non memorizza i dati di serializzazione (
SerializationInfo
lo fa)
Soluzione
Hai ragione sul fatto che la prima opzione è più lavoro. Sebbene possa potenzialmente fornirti un'implementazione più efficiente, complicherà molto le tue entità. Considera che se hai una classe Entity
di base che implementa ISerializable
, tutte le sottoclassi devono anche implementare manualmente la serializzazione !
Il trucco per far funzionare la seconda opzione è continuare a contrassegnare l'evento come non serializzabile, ma avere un secondo campo che è serializzabile e che si popoli durante gli hook di serializzazione appropriati . Ecco un esempio che ho appena scritto per mostrarti come:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var entity = new Entity();
entity.PropertyChanged += new SerializableHandler().PropertyChanged;
entity.PropertyChanged += new NonSerializableHandler().PropertyChanged;
Console.WriteLine("Before serialization:");
entity.Name = "Someone";
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, entity);
memoryStream.Position = 0;
entity = binaryFormatter.Deserialize(memoryStream) as Entity;
}
Console.WriteLine();
Console.WriteLine("After serialization:");
entity.Name = "Kent";
Console.WriteLine();
Console.WriteLine("Done - press any key");
Console.ReadKey();
}
[Serializable]
private class SerializableHandler
{
public void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(" Serializable handler called");
}
}
private class NonSerializableHandler
{
public void PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(" Non-serializable handler called");
}
}
}
[Serializable]
public class Entity : INotifyPropertyChanged
{
private string _name;
private readonly List<Delegate> _serializableDelegates;
public Entity()
{
_serializableDelegates = new List<Delegate>();
}
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, e);
}
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
[OnSerializing]
public void OnSerializing(StreamingContext context)
{
_serializableDelegates.Clear();
var handler = PropertyChanged;
if (handler != null)
{
foreach (var invocation in handler.GetInvocationList())
{
if (invocation.Target.GetType().IsSerializable)
{
_serializableDelegates.Add(invocation);
}
}
}
}
[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
foreach (var invocation in _serializableDelegates)
{
PropertyChanged += (PropertyChangedEventHandler)invocation;
}
}
}
}