Odd Generic Inheritance pattern - c#

During some research, I ran into an inheritance pattern using generics I have not seen before.
http://thwadi.blogspot.ca/2013/07/using-protobuff-net-with-inheritance.html
public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>
{
//...
}
public class DerivedClass : BaseClass<DerivedClass>
{
//...
}
Usage:
static void Main(string[] args)
{
DerivedClass derivedReference = new DerivedClass();
//this looks odd...
BaseClass<DerivedClass> baseReference = derivedReference;
//this doesn't work
//BaseClass baseClass = derivedReference;
}
I was surprised that this even worked, I had to test it myself. I still can't understand why you would want to do this.
The only thing I could come up with, is preventing different derived classes from being stored in a collection together as their base class. This may be the reason, I guess I'm just curious to the application.

It is called the Curiously recurring template pattern it is often used to allow methods in the class to use the type of the derived class as a passed in or returned parameter.
For example, this is Clone method implemented so that only each layer needs to add it's own properties to the method as it goes down the chain.
public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>, new()
{
public int Foo {get;set;}
public virtual TClass Clone()
{
var clone = new TClass();
clone.Foo = this.Foo;
return clone;
}
}
public class DerivedClass : BaseClass<DerivedClass>
{
public int Bar {get;set;}
public override DerivedClass Clone()
{
var clone = base.Clone();
clone.Bar = this.Bar;
return clone;
}
}
Usage:
static void Main(string[] args)
{
DerivedClass derivedReference = new DerivedClass();
DerivedClass clone = derivedReference.Clone();
}

As an example of usage, suppose you want to implement some chainable builder methods on the base type and derived type like this:
var d = new DerivedClass();
d.SetPropertyA("some value").SetPropertyB(1);
While SetPropertyA belongs to base class and SetPropertyB belongs to derived class.
By implementing classes like below, when chaining methods, after calling SetPropertyA because the return value is of type DerivedClass you can call SetPropertyB:
public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>
{
public string A {get ; set; }
public TClass SetPropertyA(string value)
{
this.A=value;
return this as TClass;
}
}
public class DerivedClass : BaseClass<DerivedClass>
{
public int B {get ; set; }
public DerivedClass SetPropertyB(int value)
{
this.B=value;
return this;
}
}
Then if you have some other derived classes, each of them can use the base SetPropertyA knowing the return value is of type of itself.

Related

Downcast type to base class, removing all specific attributes [duplicate]

I'm trying to refresh my memory but can't find answers with Google.
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public override void DoSomething()
{
Trace.Write("derived class");
}
}
If I create an instance of derived class, how do I convert it to it's base class so that when DoSomething() is called, it uses the base class's method only?
A dynamic cast still calls the derived class's overridden method:
DerivedClass dc = new DerivedClass();
dc.DoSomething();
(dc as BaseClass).DoSomething();
Output: "derived class"
Although this sounds irrational but it works
DerivedClass B = new DerivedClass();
BaseClass bc = JsonConvert.DeserializeObject<BaseClass>(JsonConvert.SerializeObject(B));
You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity.
Within the class itself you can non-virtually call base.AnyMethod() (whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.
You absolutely CAN (call the base method), just read up on Polymorphism:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism
Example:
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
And how to call it:
DerivedClass B = new DerivedClass();
B.DoWork(); // This calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // This calls the old method.
Try using the new keywor instead of override As far as i know this should enable that desired behavior.
I'm not realy sure about that so please don't blame me if i'm wrong!
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public new void DoSomething()
{
Trace.Write("derived class");
}
}
The solutions with new instead of override break the polymorphism. Recently I came to the same problem and implemented it the following way. My solution has the following advantages:
virtual and override stays in place;
name BaseClass is not used directly in the type cast, so if I introduce an intermediate MiddleClass in the hierarchy between BaseClass and DerivedClass, which also implements DoSomething(); then the MiddleClass's implementation won't be skipped.
This is the implementation:
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public override void DoSomething()
{
Trace.Write("derived class");
}
public void BaseDoSomething()
{
base.DoSomething();
}
}
The usage is:
DerivedClass dc = new DerivedClass();
dc.DoSomething();
dc.BaseDoSomething();
For VB.net, I've used the following code to do the conversion (shown with Lists of Objects):
Dim tempPartialList As New List(Of clsBaseData)
For Each iterClsDerivedData As clsDerivedData In ListOfDerivedDataObjects
tempPartialList.Add(CType(iterClsDerivedData, clsBaseData))
Next
Where clsBaseData is the Base Class from which clsDerivedData is made by Inheriting clsBaseData.
ListOfDerivedDataObjects is a List(Of clsDerivedData).
I have found this useful where I have Lists of several Derived Classes and I would like to operate on a property of the Base Class for all the objects in the Lists of Derived Classes. The tempPartialList is, for me, a temporary List meant to facilitate changing this property.

Abstract factory method with fixed type parameter

Is there a neat way to specify that a class must contain a factory method that returns the same kind of object as the class that overrides the abstract method? (Edit: Or as Johnathon Sullinger more eloquently puts it, [...] have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class.)
For example, if I've got two classes, SimpleFoo : BaseFoo and FancyFoo : BaseFoo, can I define an abstract factory method public TFoo WithSomeProp(SomeProp prop) where TFoo is a type parameter that is somehow fixed by the abstract method definition to the particular class that overrides it?
I had hopes of compile-time guarantees that either
a concrete WithSomeProp method definition in SomeFoo : BaseFoo will only be able to produce SomeFoos. If static abstract method definitions were legal, perhaps the following (pseudo-syntax) method extension best expresses this need:
public static abstract TFoo WithSomeProp<TFoo>(this TFoo source, SomeProp prop)
where TFoo : BaseFoo;
I don't think this is possible in C#.
or at least some way to parameterize the return type in an abstract method, e.g.
public abstract TFoo WithSomeProp<TFoo>(SomeProp prop)
where TFoo : BaseFoo;
This wouldn't prevent FancyFoo.WithSomeProp from returning SimpleFoos, but ok.
This abstract method itself seems to work, but my concrete definition then fails:
public override SimpleFoo WithSomeProp(SomeProp prop)
{
return new SimpleFoo(this.SomeOtherProp, ..., prop);
}
with the warning
no suitable method found to override
It appears to me that specifying type parameters in an abstract method does not allow fixing them in the overrides of those definitions, but rather it specifies that "A method with a type parameter should exist".
For now I simply have public abstract BaseFoo WithSomeProp(SomeProp prop);.
It sounds like what you want to do, is have a base class enforce a child class to implement a method that returns an instance of the child class itself, and not allow returning an instance of any other Type that inherits from the base class. Unfortunately, to the best of my knowledge, that is not something you can do.
You can however force the child-class to specify what it's Type is to the base class, so that the base class can then enforce that the return value must be the Type specified by the child-class.
For instance, given a base class called BaseFactory, and BaseFactory<T>, we can create an abstract class that requires children to specify to the parent, what type the creation method returns. We include a BaseFactory class so we can constrain T to only being children classes of BaseFactory.
EDIT
I'll leave the original answer below in the event that it helps, but after some thought, I think I've got a better solution for you.
You'll still need the base class to take a generic argument that defines what the child Type is. The difference now however is that the base class has a static creation method instead of instance methods. You can use this creation method to create a new instance of the child class, and optionally invoke a callback for configuring the property values on the new instance before you return it.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory, new()
{
public static TImpl Create(Action<TImpl> itemConfiguration = null)
{
var child = new TImpl();
itemConfiguration?.Invoke(child);
return child;
}
}
You then just create your children classes normally, without worrying about overriding any methods.
public class Foo : BaseFactory<Foo>
{
public bool IsCompleted { get; set; }
public int Percentage { get; set; }
public string Data { get; set; }
}
public class Bar : BaseFactory<Bar>
{
public string Username { get; set; }
}
Then you would use the factory as-such.
class Program
{
static void Main(string[] args)
{
// Both work
Bar bar1 = Bar.Create();
Foo foo1 = Foo.Create();
// Won't compile because of different Types.
Bar bar2 = Foo.Create();
// Allows for configuring the properties
Bar bar3 = Bar.Create(instanceBar => instanceBar.Username = "Jane Done");
Foo foo2 = Foo.Create(instanceFoo =>
{
instanceFoo.IsCompleted = true;
instanceFoo.Percentage = 100;
instanceFoo.Data = "My work here is done.";
});
}
Original Answer
The BaseFactory<T> will be reponsible for creating a new instance of TImpl and giving it back.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
public abstract TImpl WithSomeProp();
}
Now, your child class can be created, and inherit from BaseFactory<T>, telling the base class that T represents itself. This means the child can only ever return itself.
public class Foo : BaseFactory<Foo>
{
public override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
public override Bar WithSomeProp()
{
return new Bar();
}
}
Then you would use it like:
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.WithSomeProp();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.WithSomeProp();
}
}
If you really want to make sure that the generic specified is the same as the owning Type, you could instead make WithSomeProp a protected method, so that children classes can only see it. Then, you create a public method on the base class that can do type checking.
public abstract class BaseFactory { }
public abstract class BaseFactory<TImpl> : BaseFactory where TImpl : BaseFactory
{
protected abstract TImpl WithSomeProp();
public TImpl Create()
{
Type myType = this.GetType();
if (typeof(TImpl) != myType)
{
throw new InvalidOperationException($"{myType.Name} can not create instances of itself because the generic argument it provided to the factory is of a different Type.");
}
return this.WithSomeProp();
}
}
public class Foo : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
public class Bar : BaseFactory<Bar>
{
protected override Bar WithSomeProp()
{
return new Bar();
}
}
class Program
{
static void Main(string[] args)
{
var obj1 = new Bar();
// Works
Bar obj2 = obj1.Create();
// Won't compile because obj1 returns Bar.
Foo obj3 = obj1.Create();
}
}
Now, if you create a child class that passes a different Type as T, the base class will catch it and throw an exception.
// Throws exception when BaseFactory.Create() is called, even though this compiles fine.
public class Bar : BaseFactory<Foo>
{
protected override Foo WithSomeProp()
{
return new Foo();
}
}
Not sure if this gets you what you wanted at least, but I think this will probably be the closest thing you can get.
Inspired by Johnathon Sullinger's fine answer, here is the code I ended with. (I added a theme.)
I passed the type parameter T along with the class definition and constrained that T : Base<T>.
BaseHyperLink.cs:
public abstract class BaseHyperLink<THyperLink> : Entity<int>
where THyperLink : BaseHyperLink<THyperLink>
{
protected BaseHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id)
{
this.HyperLink = hyperLink;
this.ContentType = contentType;
this.DocumentType = documentType;
}
public Uri HyperLink { get; }
public ContentType ContentType { get; }
public DocumentType DocumentType { get; }
public abstract THyperLink WithContentType(ContentType contentType);
}
SharedHyperLink.cs:
public sealed class SharedHyperLink : BaseHyperLink<SharedHyperLink>
{
public SharedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType)
: base(id, hyperLink, contentType, documentType)
{
}
public override SharedHyperLink WithContentType(ContentType contentType)
{
return new SharedHyperLink(this.Id, contentType, this.DocumentType);
}
}
MarkedHyperLink.cs:
public sealed class MarkedHyperLink : BaseHyperLink<MarkedHyperLink>
{
public MarkedHyperLink(int? id, Uri hyperLink, ContentType contentType, DocumentType documentType, Mark mark)
: base(id, hyperLink, contentType, documentType)
{
this.Mark = mark;
}
public Mark Mark { get; }
public override MarkedHyperLink WithContentType(ContentType contentType)
{
return new MarkedHyperLink(this.Id, contentType, this.DocumentType, this.Mark);
}
}

How do I make a constructor only accessible by base class?

If I want a constructor that is only accessible from child classes I can use the protected key word in the constructor.
Now I want the opposite.
My child class should have an constructor that can be accessed by its base class but not from any other class.
Is this even possible?
This is my current code. the problem is that the child classes have a public constructor.
public abstract class BaseClass
{
public static BaseClass CreateInstance(DataTable dataTable)
{
return new Child1(dataTable);
}
public static BaseClass CreateInstance(DataSet dataSet)
{
return new Child2(dataSet);
}
}
public class Child1 : BaseClass
{
public Child1(DataTable dataTable)
{
}
}
public class Child2 : BaseClass
{
public Child2(DataSet dataSet)
{
}
}
I think you have two options:
Make the child constructor internal. This means it will be accessible from all types in the same assembly, but that should be enough in most cases.
Make the child classes nested in the base class:
public abstract class BaseClass
{
public static BaseClass CreateInstance(DataTable dataTable)
{
return new Child1(dataTable);
}
private class Child1 : BaseClass
{
public Child1(DataTable dataTable)
{
}
}
}
This way, BaseClass can use the constructor, but no other outside type can do that (or even see the child class).
I think I just solved it by myself. After reading svicks solution with nested classes, I thought why not use an protected nested class as an argument?
Nobody from outside is able to create an instance of Arg and the public contructors from my child classes can only be used by BaseClass which can create Arg<T> instances.
public abstract class BaseClass
{
protected class Arg<T>
{
public T Value { get; set; }
public Arg(T value) { this.Value = value; }
}
public static BaseClass CreateInstance(DataTable dataTable)
{
return new Child1(new Arg<DataTable>(dataTable));
}
public static BaseClass CreateInstance(DataSet dataSet)
{
return new Child2(new Arg<DataSet>(dataSet));
}
}
public class Child1 : BaseClass
{
public Child1(Arg<DataTable> arg) : this(arg.Value) { }
private Child1(DataTable dataTable)
{
}
}
public class Child2 : BaseClass
{
public Child2(Arg<DataSet> arg) : this(arg.Value) { }
public Child2(DataSet dataSet)
{
}
}
Answer to the question is "NO"
There is no such thing exists in the OOP that allow child class constructor to visible only to the Base Class of it...
One could enforce the desired behavior at run-time by having the base constructor accept a ref parameter, and do something like (not threadsafe):
private int myMagicCounter;
public DerivedClass makeDerived(whatever) // A factory method
{
DerivedClass newThing;
try
{
... do whatever preparation
newThing = new DerivedClass(ref myMagicCounter, whatever);
}
finally
{
... do whatever cleanup
}
return newThing;
}
BaseClass(ref int magicCounter, whatever...)
{
if (magicCounter != myMagicCounter)
throw new InvalidOperationException();
myMagicCounter++;
if (magicCounter != myMagicCounter)
throw new InvalidOperationException();
}
Note that it will be impossible for a derived class constructor call to get control without having done the factory method's preparation, or to return control to its caller without doing the factory method's cleanup. There will, however, be nothing to prevent the derived-class constructor from passing its partially-constructed instance to outside code which may do whatever it likes with it for an arbitrary amount of time before returning control to the factory method.
Pass and register a factory delegate from the type initializer of derived classes then you just get the job done:
public abstract class BaseClass {
static readonly Dictionary<Type, Delegate>
m_factories = new Dictionary<Type, Delegate> { };
public static BaseClass CreateInstance(DataTable dataTable) {
var type = typeof(Child1);
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
return (Child1)m_factories[type].DynamicInvoke(dataTable);
}
public static BaseClass CreateInstance(DataSet dataSet) {
var type = typeof(Child2);
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
return (Child2)m_factories[type].DynamicInvoke(dataSet);
}
protected static void AddFactory<TArgs, T>(Func<TArgs, T> factory) {
m_factories.Add(typeof(T), factory);
}
}
public class Child1:BaseClass {
Child1(DataTable dataTable) {
}
static Child1() {
BaseClass.AddFactory((DataTable dt) => new Child1(dt));
}
}
public class Child2:BaseClass {
Child2(DataSet dataSet) {
}
static Child2() {
BaseClass.AddFactory((DataSet ds) => new Child2(ds));
}
}
public static class TestClass {
public static void TestMethod() {
var child2 = BaseClass.CreateInstance(new DataSet { });
var child1 = BaseClass.CreateInstance(new DataTable { });
}
}
If all of the derived classes inherited from the base class directly then don't you worry about the collision of registration -- no body can access a constructor from another class.
For TArgs of Func<TArgs, T> you might want to declare it like variadic generic arguments although it's just not a feature of C♯, Tuple is one of the approaches to simulate it. For more information on this topic, you might want to have a look at:
Simulate variadic templates in c#

How can a method in a base class return a more derived object based on the type of the object it is called on?

Suppose you have two classes, as in the example below.
How would you modify SplitObject such that it always returns an object of type t, such as in Main(), where it should return an object of type DerivedClass?
I'm guessing the solution would involve reflection? I haven't learned anything about reflection yet, so I don't know how this would work.
public class BaseClass
{
float _foo;
public BaseClass(float foo){_foo = foo}
public BaseClass SplitObject()
{
Type t = GetType();
// Do something with t
_foo = _foo/2f;
return new BaseClass(_foo); // I want to construct an
// object of type t instead
// of type BaseClass
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(float foo) : base(foo){}
}
class Program
{
static void Main()
{
BaseClass foo = new DerivedClass(1f);
BaseClass bar = foo.SplitObject(); // should return a DerivedObject
}
}
If you really wanted to use reflection, you could do something like:
return (BaseClass)Activator.CreateInstance(GetType(), _foo);
Of course, there is now an implicit contract that all derived classes must implement such a constructor. Unfortunately, such contracts cannot be specified in the current type-system; so violations will not be caught at compile-time. It would be much better to go with erash's idea. I would do something like:
//... Base class:
public BaseClass SplitObject()
{
_foo = _foo / 2f;
return NewInstance(_foo);
}
protected virtual BaseClass NewInstance(float foo)
{
return new BaseClass(foo);
}
//... Derived class:
protected override BaseClass NewInstance(float foo)
{
return new DerivedClass(foo);
}
No reflection required -- just make SplitObject() be virtual and implement it differently in your derived classes.
Another option would be to extract the Split behavior into an interface, say ISplittable<T>
public class BaseClass
{
public virtual BaseClass SplitObject()
{
BaseClass splitObject = new BaseClass();
//initialize the split object
return splitObject;
}
}
public class DerivedClass : BaseClass
{
public override BaseClass SplitObject()
{
DerivedClass derivedSplitObject = new DerivedClass();
//initialize the derived split object
return derivedSplitObject;
}
}
}
If you only want the code to appear in one place (better for maintenance, especially if there are many derived types), you will need to use reflection:
public class BaseClass
{
float _foo;
public BaseClass(float foo){_foo = foo;}
public BaseClass SplitObject()
{
Type t = GetType();
_foo = _foo / 2f;
//Find the constructor that accepts float type and invoke it:
System.Reflection.ConstructorInfo ci = t.GetConstructor(new Type[]{typeof(float)});
object o=ci.Invoke(new object[]{_foo});
return (BaseClass)o;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(float foo) : base(foo) { }
}
class Program
{
static void Main()
{
BaseClass foo = new DerivedClass(1f);
//Cast the BaseClass to DerivedClass:
DerivedClass bar = (DerivedClass)foo.SplitObject();
}
}

How do I create clone of object in base class?

I need a method that creates an empty clone of an object in a base class? For instance:
public class ChildClass : ParentClass
{
public ChildClass()
{
}
}
public class ParentClass
{
public SomeMethod()
{
// I want to create an instance of the ChildClass here
}
}
Up until now, we have an abstract method defined in the parent class. And, all of the child classes implement them. But, the implementation is the same for all, just a different type.
public class ChildClass : ParentClass
{
public ChildClass()
{
}
public ParentClass CreateEmpty()
{
return new ChildClass();
}
}
public class ParentClass
{
public SomeMethod()
{
// I want to create an instance of the ChildClass here
ParentClass empty = CreateEmpty();
}
public abstract ParentClass CreateEmpty();
}
Is there any way to do this from the parent class so that I don't have to keep implementing the same logic for each different child class? Note that there may be more levels of inheritance (i.e. ChildChildClass : ChildClass : ParentClass).
If using reflection isn't a problem to you, you could do it using Activator class:
//In parent class
public ParentClass CreateEmpty()
{
return (ParentClass)Activator.CreateInstance(this.GetType());
}
This will return empty object of the type you want. Notice that this method does not need to be virtual.
On the other hand, I think that your current approach is perfectly fine, few more lines of code aren't so bad.
You can make a deep clone of the object using the binary serializer.
EDIT: Just noticed the word "empty" next to clone (which I thought was an oxymoron). Leaving this response up anyhow hoping it will help others that find this question because they are looking to do a regular clone.
This is somewhat experimental. I don't know whether this will lead to a cyclic dependency. Haven't touched C# for some months.
public class ParentClass<T> where T : ParentClass<T>, new() { // fixed
public ParentClass() {
var x = new T(); // fixed, was T.new()
}
}
public class ChildClass : ParentClass<ChildClass> {
public ChildClass() { }
}
Otherwise go for the ReflectionCode by Ravadre.
I'm using the following pattern.
Pros:
This pattern secure the type-safety of cloning in private and public sides of classes.
The output class will be always correct.
You never forgot override the "clone" method. The "MyDerivedClass" never returns another class than the "MyDerivedClass".
Cons:
For one class, you need create one interface and two classes (prototype and final)
Sample:
// Common interface for cloneable classes.
public interface IPrototype : ICloneable {
new IPrototype Clone();
}
// Generic interface for cloneable classes.
// The 'TFinal' is finaly class (type) which should be cloned.
public interface IPrototype<TFinal> where TFinal : IPrototype<TFinal> {
new TFinal Clone();
}
// Base class for cloneable classes.
// The 'TFinal' is finaly class (type) which should be cloned.
public abstract class PrototypeBase<TFinal> : IPrototype<TFinal> where TFinal : PrototypeBase<TFinal> {
public TFinal Clone() {
TFinal ret = this.CreateCloneInstance();
if ( null == ret ) {
throw new InvalidOperationException( "Clone instance was not created." );
}
this.FillCloneInstance( ret );
return ret;
}
// If overriden, creates new cloned instance
protected abstract TFinal CreateCloneInstance();
// If overriden, fill clone instance with correct values.
protected abstract void FillCloneInstance( TFinal clone );
IPrototype IPrototype.Clone() { return this.Clone(); }
object ICloneable.Clone() { return this.Clone(); }
}
// Common interface for standalone class.
public interface IMyStandaloneClass : IPrototype<IMyStandaloneClass> {
string SomeText{get;set;}
string SomeNumber{get;set;}
}
// The prototype class contains all functionality exception the clone instance creation.
public abstract class MyStandaloneClassPrototype<TFinal> : PrototypeBase<TFinal>, IMyStandaloneClass where TFinal : MyStandaloneClassPrototype<TFinal> {
public string SomeText {get; set;}
public int SomeNumber {get; set}
protected override FillCloneInstance( TFinal clone ) {
// Now fill clone with values
clone.SomeText = this.SomeText;
clone.SomeNumber = this.SomeNumber;
}
}
// The sealed clas contains only functionality for clone instance creation.
public sealed class MyStandaloneClass : MyStandaloneClassPrototype<MyStandaloneClass> {
protected override MyStandaloneClass CreateCloneInstance() {
return new MyStandaloneClass();
}
}
public interface IMyExtendedStandaloneClass : IMyStandaloneClass, IPrototype<IMyExtendedStandaloneClass> {
DateTime SomeTime {get; set;}
}
// The extended prototype of MyStandaloneClassPrototype<TFinal>.
public abstract class MyExtendedStandaloneClassPrototype<TFinal> : MyStandaloneClassPrototype<TFinal> where TFinal : MyExtendedStandaloneClassPrototype<TFinal> {
public DateTime SomeTime {get; set;}
protected override FillCloneInstance( TFinal clone ) {
// at first, fill the base class members
base.FillCloneInstance( clone );
// Now fill clone with values
clone.SomeTime = this.SomeTime;
}
}
public sealed class MyExtendedStandaloneClass : MyExtendedStandaloneClassPrototype<TFinal> {
protected override MyExtendedStandaloneClass CreateCloneInstance() {
return new MyExtendedStandaloneClass
}
}

Categories

Resources