我有一个基类,它有一些使用类型推断的功能......
public abstract class Processor<T>
{
...
public IProcessBuilder<T, TResult> Process<TResult>(Expression<Func<T, TResult>> propertyOfT)
{
}
public abstract void SetProcessors();
}
然后我有两个班:
public class EntityBase
{
public string Name { get; set; }
}
public class EntityChild : EntityBase
{
public string Description { get; set; }
}
在这两个中,我还有两个配置这两个类的处理器:
public class EntityBaseProcessor : Processor<EntityBase>
{
public override void SetProcessors()
{
base.SetProcessors();
this.Process(entity => entity.Name)
.DoSomething();
}
}
现在问题是我想为子类重用已配置的基本实体类进程以避免代码重复:
public class EntityChildProcessor: EntityBaseProcessor
{
public override void SetProcessors()
{
base.SetProcessor();
this.Process(entity => /* entity.Description is of course missing */)
.DoSomething();
}
}
我显然很累,因为我似乎无法找到重用处理器类的可行方法,因为继承的处理器类也应该使用继承的实体类进行处理。
我当然可以重复代码并将我的其他处理器编写为:
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();
}
}
答案 0 :(得分:1)
使EntityBaseProcessor也是通用的:
public class EntityBaseProcessor<T> : Processor<T> where T : EntityBase
public class EntityChildProcessor<T> : EntityBaseProcessor<T> where T : EntityChild
或者:(您可以使用非通用EntityChildProcessor
的简单性来换取永久设置T
类型的缺点)
public sealed class EntityChildProcessor : EntityBaseProcessor<EntityChild>
答案 1 :(得分:0)
将EntityBaseProcessor
声明为通用类是多么合理?像这样:
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();
}
}