Independent type

I create the following class:

abstract class Foo { protected abstract void Process(FooProcessor<T> processor) } 

I need T be the type of the child class Foo :

 class FooChild : Foo { protected override void Process(FooProcessor<FooChild> processor) { } } 

Is it possible? If so, how?

+6
source share
2 answers

Something like self-restraint will allow you to expose derived types while holding back:

 abstract class Foo<T> where T : Foo<T> { protected abstract void Process(FooProcessor<T> processor); } 

Then derived types define themselves as a target:

 class FooChild : Foo<FooChild> { protected override void Process(FooProcessor<FooChild> processor) { } } 

Please note that this design tends to have only a small set of uses. In addition, you lose the ability to refer to Foo as a base without specifying its general type.

There is also a blog post from Eric Lippert about how to abuse this design, so you might consider what it is that you are actually trying to accomplish by wanting your protected method to reference the derived class directly.

You might be better off using interfaces to encapsulate the behavior you are trying to achieve.

+6
source

You mean this:

 class FooProcessor<T> { } abstract class Foo<T> { protected abstract void Process(FooProcessor<T> processor); } class FooChild : Foo<FooChild> { protected override void Process(FooProcessor<FooChild> processor) { } } 

It would be easier to implement with an interface:

 interface FooProcessor<T> { } interface Foo<T> { void Process(FooProcessor<T> processor); } class FooChild : Foo<FooChild> { void Foo<FooChild>.Process(FooProcessor<FooChild> processor) { this.Process((FooProcessorFooChild)processor); } protected void Process(FooProcessorFooChild processor) { } } class FooProcessorFooChild : FooProcessor<FooChild> { } 
+1
source

All Articles