2011-10-13 4 views
1

누가이 매트릭스 클래스에 대한 DeepCopy 루틴을 작성하도록 도와 줄 수 있습니까? 나는 C#에서 많은 경험을하지 못했다.C# DeepCopy 루틴

public class Matrix<T> 
{ 
    private readonly T[][] _matrix; 
    private readonly int row; 
    private readonly int col; 

    public Matrix(int x, int y) 
    { 
     _matrix = new T[x][]; 
     row = x; 
     col = y; 
     for (int r = 0; r < x; r++) 
     { 
      _matrix[r] = new T[y]; 
     } 
    } 
} 

사전

+1

이 http://stackoverflow.com/questions/6052756/c-thread-safe-deep-copy –

답변

2

깊은 복사의 가장 간단한 방법은 (예를 BinaryFormatter을위한) 직렬의 어떤 종류를 사용하는 것입니다, 그러나 이것은 Serializable로 장식 할뿐만 아니라 당신의 유형을 필요로 감사뿐만 아니라 유형 T.

그 예가 구현 될 수있다 :

[Serializable] 
public class Matrix<T> 
{ 
    // ... 
} 

public static class Helper 
{ 
    public static T DeepCopy<T>(T obj) 
    { 
    using (var stream = new MemoryStream()) 
    { 
     var formatter = new BinaryFormatter(); 
     formatter.Serialize(stream, obj); 
     stream.Position = 0; 
     return (T) formatter.Deserialize(stream); 
    } 
    } 
} 

여기서 문제는, 당신은 통제의 O를 가지고 있지 않은지 ver 제네릭 형식 매개 변수로 제공되는 형식입니다. 어떤 타입의 타입을 복제 할 것인지 더 알지 못하면, T에 generic 타입 제약을 두어 ICloneable을 구현하는 타입만을 받아들이는 옵션이있을 수 있습니다.

경우에 당신은과 같이 Matrix<T>를 복제 할 수 있습니다 :

public class Matrix<T> where T: ICloneable 
{ 
    // ... fields and ctor 

    public Matrix<T> DeepCopy() 
    { 
    var cloned = new Matrix<T>(row, col); 
    for (int x = 0; x < row; x++) { 
     for (int y = 0; y < col; y++) { 
     cloned._matrix[x][y] = (T)_matrix[x][y].Clone(); 
     } 
    } 
    return cloned; 
    } 
} 
+0

굉장한 도움이 될 것입니다. 그냥 후 무엇. 당신은 전설입니다! – nixgadgets

+0

도와 드리겠습니다 :-) –