Implementation of the universal method

I created an interface with one method, the ability to copy the contents of one object to another object of the same type (the actual functionality is not relevant to the issue).

public interface IDeepClonable
{
    void DeepClone<T>(T other);
}

I am having problems with the correct implementation.

I would like it to be implemented (where is it inside ClassA that implements IDeepClonable)

public void DeepClone<ClassA>(ClassA other)
{
    this.A = other.A;
}

However, this does not work, since the β€œother” object is not recognized by the compiler as an instance of the ClassA class (why?)

This also does not work, since it gives "restrictions for a parameter of type T, which must correspond to the interface method (...).

public void DeepClone<T>(T other) where T : ClassA
{
    this.A= other.A;
}

I can solve all problems by changing the interface to take an object instead of a general restriction, but I was hoping for a more elegant solution.

, , .

+3
2

CRTP.

public interface IDeepClonable<out T> where T : IDeepClonable<T>
{
    void DeepClone(T other);
}

public class ClassA : IDeepClonable<ClassA> {
    void DeepClone(ClassA other) { ... }
}

, , IDeepClonable, , .

CLR , , .

+5

, , , :

public class ClassA : IDeepClonable 
{ 
    void DeepClone<T>(T other) { /* some implementation here */ } 
} 

- , .

, , , :

public interface IDeepClonable 
{ 
    void DeepClone(IDeepClonable other); 
} 

public class ClassA : IDeepClonable 
{ 
    void DeepClone(IDeepClonable other)
    {
         // just to be sure ....
         if (other is ClassA) 
         {
             var o = (ClassA)other;
             this.A = o.A; 
         }
    } 
} 
0
source

All Articles