Array Copy

1,2次元配列のコピー拡張的な何か。

配列のCopyToってなんで戻り値で返してくれないんだろうっていつも思ってる。

static class ArrayExtension {
	public static T[] CreateDeepClone<T>( this T[] source ) {
		if ( !typeof( T ).IsValueType ) {
			throw new ArgumentException( typeof( T ).Name + "は値型ではありません" );
		}

		var destination = new T[source.Length];
		source.CopyTo( destination, 0 );

		return destination;
	}

	public static T[,] CreateDeepClone<T>( this T[,] source ) {
		if ( !typeof( T ).IsValueType ) {
			throw new ArgumentException( typeof( T ).Name + "は値型ではありません" );
		}

		var destination = new T[source.GetLength( 0 ), source.GetLength( 1 )];

		for ( int i = 0; i < source.GetLength( 0 ); i++ ) {
			for ( int j = 0; j < source.GetLength( 1 ); j++ ) {
				destination[i, j] = source[i, j];
			}
		}

		return destination;
	}

	public static T[] CreateDeepClone<T>( this T[] source, Func<T[], T[], T[]> copyFunction ) {
		var destination = new T[source.Length];
		return copyFunction(source, destination);
	}
}
void Test() {
	int[] a = new[] {1, 2, 3, 4, 5, 6, 7};
	var b = a.CreateDeepClone();
	var c = a;
	a[0] = 10;
	Console.WriteLine(b[0]);
	Console.WriteLine(c[0]);

	C[] m = new[] { new C(1), new C(2), new C(3), new C(4), new C(5), new C(6), new C(7) };
	var n = m.CreateDeepClone((source,des)=>{
		for (int i = 0; i < source.Length; i++) {
                	des[i]=new C(source[i].Value);
		}
		return des;
	} );
	var o = m;
	m[0].Value = 10;
	Console.WriteLine( n[0].Value );
	Console.WriteLine( o[0].Value );
}

internal class C {
	public int Value;

	public C(int v) {
		Value = v;
	}
}

拡張メソッドって初めて作ったけど意外と使えるかも。
Emunにも拡張できるとは思わなかった。

コピーってICloneableとかあるけどマジ使えんIFだよな。さっさと廃止すればよかったのに。
IDeepCloneableとかじゃないとわからんだろ。

なんで、Funcでお茶を濁してみる。
それはそれで引数に名前付けられないから問題(実装がわかってないと使えないってこと)は一緒なんだがw

ちゃんとdelegate用意するにもクラス化しないといけないしなー。
自分でIDeepCloneable作るのが一番っぽいと思う。