我有一个DeepCopy方法,它序列化参数中传递的对象并返回反序列化的对象以进行深层复制。
我的方法是:
public static class GenericCopier<T>
{
public static T DeepCopy(object objectToCopy)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, objectToCopy);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)binaryFormatter.Deserialize(memoryStream);
}
}
}
如果传递给参数的对象不包含任何BitmapImage字段和属性,则效果很好。
public class MyClass
{
public string TestString {get; set;}
public BitmapImage TestImage { get; set;}
}
如果我制作MyClass的DeepCopy,
MyClass orginal = new MyClass(){ TestString = "Test"};
MyClass copy = GenericCopier<MyClass>.DeepCopy(orginal);
它抛出异常
Type&#39; System.Windows.Media.Imaging.BitmapImage&#39;在Assembly中未标记为可序列化
我找到了一个序列化BitmapImage here
的方法但是,我如何混合两种类型的序列化(BinaryFormatter&amp; PngBitmapEncoder)来序列化MyClass?
答案 0 :(得分:1)
这里有两个选项:
选项1:实施ISerializable
和快照到PNG
这里必须做的是让所有包含BitmapImage
的类实现ISerializable
接口,然后在GetObjectData
中返回表示图像编码的字节数组,实例PNG。然后在deserialization constructor中将PNG解码为新的BitmapImage
。
请注意,这会使图像快照,因此可能会丢失一些WPF数据。
由于您可能有多个包含BitmapImage
的类,最简单的方法是引入一些包含器结构,其中隐式转换为BitmapImage
,如下所示:
[Serializable]
public struct SerializableBitmapImageWrapper : ISerializable
{
readonly BitmapImage bitmapImage;
public static implicit operator BitmapImage(SerializableBitmapImageWrapper wrapper)
{
return wrapper.BitmapImage;
}
public static implicit operator SerializableBitmapImageWrapper(BitmapImage bitmapImage)
{
return new SerializableBitmapImageWrapper(bitmapImage);
}
public BitmapImage BitmapImage { get { return bitmapImage; } }
public SerializableBitmapImageWrapper(BitmapImage bitmapImage)
{
this.bitmapImage = bitmapImage;
}
public SerializableBitmapImageWrapper(SerializationInfo info, StreamingContext context)
{
byte[] imageBytes = (byte[])info.GetValue("image", typeof(byte[]));
if (imageBytes == null)
bitmapImage = null;
else
{
using (var ms = new MemoryStream(imageBytes))
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmapImage = bitmap;
}
}
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
byte [] imageBytes;
if (bitmapImage == null)
imageBytes = null;
else
using (var ms = new MemoryStream())
{
BitmapImage.SaveToPng(ms);
imageBytes = ms.ToArray();
}
info.AddValue("image", imageBytes);
}
#endregion
}
public static class BitmapHelper
{
public static void SaveToPng(this BitmapSource bitmap, Stream stream)
{
var encoder = new PngBitmapEncoder();
SaveUsingEncoder(bitmap, stream, encoder);
}
public static void SaveUsingEncoder(this BitmapSource bitmap, Stream stream, BitmapEncoder encoder)
{
BitmapFrame frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
encoder.Save(stream);
}
public static BitmapImage FromUri(string path)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(path);
bitmap.EndInit();
return bitmap;
}
}
然后按如下方式使用:
[Serializable]
public class MyClass
{
SerializableBitmapImageWrapper testImage;
public string TestString { get; set; }
public BitmapImage TestImage { get { return testImage; } set { testImage = value; } }
}
public static class GenericCopier
{
public static T DeepCopy<T>(T objectToCopy)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, objectToCopy);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)binaryFormatter.Deserialize(memoryStream);
}
}
}
选项2:使用序列化代理直接克隆BitmapImage
事实证明BitmapImage
有一个Clone()
方法,所以有理由问:是否有可能覆盖二进制序列化以将原始内容替换为克隆,而不实际序列化?这样做可以避免快照到PNG的潜在数据丢失,因此看起来更合适。
事实上,可以使用serialization surrogates将{(3}}代理替换位图图像,该代理包含由代理人创建的克隆副本的ID。
public static class GenericCopier
{
public static T DeepCopy<T>(T objectToCopy)
{
var selector = new SurrogateSelector();
var imageSurrogate = new BitmapImageCloneSurrogate();
imageSurrogate.Register(selector);
BinaryFormatter binaryFormatter = new BinaryFormatter(selector, new StreamingContext(StreamingContextStates.Clone));
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, objectToCopy);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)binaryFormatter.Deserialize(memoryStream);
}
}
}
class CloneWrapper<T> : IObjectReference
{
public T Clone { get; set; }
#region IObjectReference Members
object IObjectReference.GetRealObject(StreamingContext context)
{
return Clone;
}
#endregion
}
public abstract class CloneSurrogate<T> : ISerializationSurrogate where T : class
{
readonly Dictionary<T, long> OriginalToId = new Dictionary<T, long>();
readonly Dictionary<long, T> IdToClone = new Dictionary<long, T>();
public void Register(SurrogateSelector selector)
{
foreach (var type in Types)
selector.AddSurrogate(type, new StreamingContext(StreamingContextStates.Clone), this);
}
IEnumerable<Type> Types
{
get
{
yield return typeof(T);
yield return typeof(CloneWrapper<T>);
}
}
protected abstract T Clone(T original);
#region ISerializationSurrogate Members
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
var original = (T)obj;
long cloneId;
if (original == null)
{
cloneId = -1;
}
else
{
if (!OriginalToId.TryGetValue(original, out cloneId))
{
Debug.Assert(OriginalToId.Count == IdToClone.Count);
cloneId = OriginalToId.Count;
OriginalToId[original] = cloneId;
IdToClone[cloneId] = Clone(original);
}
}
info.AddValue("cloneId", cloneId);
info.SetType(typeof(CloneWrapper<T>));
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
var wrapper = (CloneWrapper<T>)obj;
var cloneId = info.GetInt64("cloneId");
if (cloneId != -1)
wrapper.Clone = IdToClone[cloneId];
return wrapper;
}
#endregion
}
public sealed class BitmapImageCloneSurrogate : CloneSurrogate<BitmapImage>
{
protected override BitmapImage Clone(BitmapImage original)
{
return original == null ? null : original.Clone();
}
}
在此实现中,您的主要类保持不变:
[Serializable]
public class MyClass
{
BitmapImage testImage;
public string TestString { get; set; }
public BitmapImage TestImage { get { return testImage; } set { testImage = value; } }
}
尴尬的是,虽然BitmapImage
有Clone
方法,但实际上并没有实现ICloneable
接口。如果有,上面的代码可能看起来更干净,因为我们可以简单地克隆每个可克隆对象,而不是为BitmapImage
调用特定方法。