I'm building the following class:
abstract class Foo
{
protected abstract void Process(FooProcessor<T> processor)
}
What I need is to make T
be the type of child Foo
class:
class FooChild : Foo
{
protected override void Process(FooProcessor<FooChild> processor)
{
}
}
Is it achievable? If so, how?
Something like a self-constraint will allow you to expose derived types and also constrain at the same time:
abstract class Foo<T> where T : Foo<T>
{
protected abstract void Process(FooProcessor<T> processor);
}
Then derived types define themselves as the target:
class FooChild : Foo<FooChild>
{
protected override void Process(FooProcessor<FooChild> processor)
{
}
}
Please note though that this design tends to only have a small set of uses. Also, you lose the ability to refer to Foo
as a base without specifying it's generic type.
There is also a blog post from Eric Lippert about how it is possible to abuse this design, so you might want to consider what it is you are actually trying to achieve by wanting to have your protected method reference the derived class directly.
You may be better off using interfaces to encapsulate the behaviour you are trying to achieve.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments