|
-
February 4th, 2011, 02:21 AM
#1
Type-safe copy interface
Hi,
I am trying to implement an interface in C# that requires implementing classes to return a copy of themselves in a type-safe manner (i.e. returning the implementing class' own type, NOT an IExample type). I google'd around a bit, but did not find a satisfactory design pattern. The solution I hacked together was (abstracting everything possible away):
Code:
public interface IExampleCore
{
bool exampleCommonMethod();
bool anotherExample();
IExampleCore deepCopyCore();
}
public interface IExample<T> : IExampleCore where T : IExample<T>
{
T deepCopy();
}
And finally implementing an object like:
Code:
public class ExampleClass : IExample<ExampleClass>
{
public bool exampleCommonMethod() { ... }
public bool anotherExample() { ... }
public ExampleClass deepCopy() { ... }
public IExampleCore deepCopyCore() { return this.deepCopy(); }
}
This seems to compile OK, but it seems like a long way to go to implement a type safe deep copy. I am particularly concerned about the where directive wherein T is used in the constraint. This seems circular, however logical it seems in my mind. Is this appropriate? Is there a better way?
Note I do also want to support a non-type safe call to anything implemeting IExampleCore (or IExample<T>, by extension) that returns merely an IExampleCore (hence the deepCopyCore() method) in addition to the type-safe deepCopy().
Any advice would be much appreciated. Thanks.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|