C# 如何从 [Serializable] INotifyPropertyChanged 实现器中排除不可序列化的观察者?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/618994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to exclude nonserializable observers from a [Serializable] INotifyPropertyChanged implementor?
提问by skolima
I have almost a hundred of entity classes looking like that:
我有将近一百个实体类看起来像这样:
[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));
}
}
Notice the [field:NonSerialized]
attribute on PropertyChanged
. This is necessary as some of the observers (in my case - a grid displaying the entities for edition) may not be serializable, and the entity has to be serializable, because it is provided - via remoting - by an application running on a separater machine.
注意 上的[field:NonSerialized]
属性PropertyChanged
。这是必要的,因为一些观察者(在我的情况下 - 显示编辑实体的网格)可能无法序列化,并且实体必须是可序列化的,因为它是由在单独的机器上运行的应用程序通过远程处理提供的.
This solution works fine for trivial cases. However, it is possible that some of the observers are [Serializable]
, and would need to be preserved. How should I handle this?
此解决方案适用于琐碎的情况。但是,某些观察者可能是[Serializable]
,并且需要保留。我该如何处理?
Solutions I am considering:
我正在考虑的解决方案:
- full
ISerializable
- custom serialization requires writing a lot of code, I'd prefer not to do this - using
[OnSerializing]
and[OnDeserializing]
attributes to serializePropertyChanged
manually - but those helper methods provide onlySerializationContext
, which AFAIK does not store serialization data (SerializationInfo
does that)
- 完全
ISerializable
自定义序列化需要编写大量代码,我不想这样做 - 使用
[OnSerializing]
和[OnDeserializing]
属性PropertyChanged
手动序列化- 但这些辅助方法仅提供SerializationContext
AFAIK 不存储序列化数据(SerializationInfo
这样做)
采纳答案by Kent Boogaart
You're right that the first option is more work. While it can potentially give you a more efficient implementation, it will complicate your entities a lot. Consider that if you have a base Entity
class that implements ISerializable
, all subclasses also have to manually implement serialization!
你是对的,第一个选择是更多的工作。虽然它可能会为您提供更有效的实现,但它会使您的实体复杂化很多。考虑一下,如果您有一个Entity
实现的基类ISerializable
,那么所有子类也必须手动实现序列化!
The trick to getting the second option to work, is to continue marking the event as non-serializable, but to have a second field that isserializable and that you populate yourself during the appropriate serialization hooks. Here is a sample I just wrote to show you how:
使第二个选项起作用的技巧是继续将事件标记为不可序列化,但要有一个可序列化的第二个字段,并在适当的序列化挂钩期间填充自己。这是我刚刚写的一个示例,用于向您展示如何操作:
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;
}
}
}
}