Output Type and Inheritance

I have a base class that has some functionality that uses type inference ...

public abstract class Processor<T> { ... public IProcessBuilder<T, TResult> Process<TResult>(Expression<Func<T, TResult>> propertyOfT) { } public abstract void SetProcessors(); } 

Then I have two classes:

 public class EntityBase { public string Name { get; set; } } public class EntityChild : EntityBase { public string Description { get; set; } } 

And for these two, I also have two processors that configure these two classes:

 public class EntityBaseProcessor : Processor<EntityBase> { public override void SetProcessors() { base.SetProcessors(); this.Process(entity => entity.Name) .DoSomething(); } } 

Now the problem is that I would like to reuse the configured process of the entity base class for the child class, as well as avoid code duplication:

 public class EntityChildProcessor: EntityBaseProcessor { public override void SetProcessors() { base.SetProcessor(); this.Process(entity => /* entity.Description is of course missing */) .DoSomething(); } } 

Question

I'm apparently tired because I cannot find a possible way to reuse processor classes, because a legacy processor class must also use a class of inherited entities for processing.

I can, of course, repeat the code and write my other processor as:

 public class EntityChildProcessor: Processor<EntityChild> { public override void SetProcessors() { base.SetProcessor(); // repeated code for inherited property this.Process(entity => entity.Name) .DoSomething(); this.Process(entity => entity.Description) .DoSomething(); } } 
+4
source share
2 answers

How would you be wise to declare EntityBaseProcessor as a generic class? Something like that:

 public class EntityBaseProcessor<TEntityBase> : Processor<TEntityBase> where TEntityBase : EntityBase { public override void SetProcessors() { base.SetProcessors(); this.Process(entity => entity.Name) .DoSomething(); } } public class EntityChildProcessor : EntityBaseProcessor<EntityChild> { public override void SetProcessors() { base.SetProcessors(); this.Process(entity => entity.Description) .DoSomething(); } } 
0
source

Create an EntityBaseProcessor as well:

 public class EntityBaseProcessor<T> : Processor<T> where T : EntityBase public class EntityChildProcessor<T> : EntityBaseProcessor<T> where T : EntityChild 

Or: (you can exchange the simplicity of the non-core EntityChildProcessor for the lack of a permanent installation of type T )

 public sealed class EntityChildProcessor : EntityBaseProcessor<EntityChild> 
+1
source

All Articles