Skip to content

Instantly share code, notes, and snippets.

@step5748
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save step5748/152ee469694115a93c9f to your computer and use it in GitHub Desktop.
Save step5748/152ee469694115a93c9f to your computer and use it in GitHub Desktop.
C#によるシリアライズを利用した汎用のオブジェクトのディープコピー処理
//===========================================================================
//!
//! @file DeepCopy.cs
//! @brief シリアライズを利用した汎用のオブジェクトのディープコピー処理
//!
//! @note
//! BinaryFormatterを使用してMemoryStreamに対してシリアライズ/デシリアライズを行い
//! オブジェクトのメモリイメージのコピーを作成するテクニックです。
//! 理論上、Serializable属性を付与したすべてのオブジェクトに対してディープコピーが可能になります。
//!
//! ICloneableインタフェース、MemberWiseCloneメソッドを使用したシャローコピーについては
//! 以下の記事を参考にしてください。
//! http://d.hatena.ne.jp/tekk/20091012/1255362429
//!
//===========================================================================
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
/*
// コピーしたいテストクラス
[System.Serializable]
public class item
{
public int id;
public string name;
}
// コピー処理サンプル
void Test()
{
item a = new item();
a.id = 12345;
a.name = "hello";
Debug.Log("a: id " + a.id.ToString() + " name " +a.name );
item b;
// 拡張メソッド
b = ( item )a.DeepCopy();
Debug.Log("b: id " + b.id.ToString() + " name " +b.name );
// ジェネリックメソッド
b = DeepCopyHelper.DeepCopy< item >( a );
b.id = 54635;
Debug.Log("b: id " + b.id.ToString() + " name " +b.name );
}
*/
static class DeepCopyUtils
{
public static object DeepCopy(this object target)
{
object result;
BinaryFormatter b = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
try
{
b.Serialize(mem, target);
mem.Position = 0;
result = b.Deserialize(mem);
}
finally
{
mem.Close();
}
return result;
}
}
public static class DeepCopyHelper
{
public static T DeepCopy<T>(T target)
{
T result;
BinaryFormatter b = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
try
{
b.Serialize(mem, target);
mem.Position = 0;
result = (T)b.Deserialize(mem);
}
finally
{
mem.Close();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment