假设我的数据访问层中有以下类结构:
interface IBehavior<in T>
{
void Load(T model);
}
class ModelManager<T>
{
ModelManager(IEnumerable<IBehavior<T>> behaviors) { ... }
void Load(T model)
{
foreach (var behavior in behaviors) {
behavior.Load(model)
}
}
}
这让我有我的模型可以实现的各种接口,以及处理这些接口的可重用行为:
interface IUnique { ... }
class UniqueBehavior : IBehavior<IUnique> { ... }
interface ITimestampable { ... }
class TimestampableBehavior : IBehavior<ITimestampable> { ... }
并且经理很乐意接受这些,因为IBehavior<T>
.
class MyModel : IUnique, ITimestampable { ... }
new ModelManager<MyModel>(new IBehavior<MyModel>[] {
new UniqueBehavior(),
new TimestampableBehavior()
});
极好的。
但是现在,我想让每个行为也将一组 LINQ 过滤器应用于实体。我的第一个想法是将此方法添加到IBehavior<T>
:
void ApplyFilters<IEnumerable>(ref IEnumerable<T> models)
...其中实施行为将Where
自行决定将一组子句应用于枚举。
However, as it turns out, ref parameters don't allow type variation. I'm struggling to find a way to implement this kind of functionality while maintaining both type safety and the contravariant nature of the interface. Any ideas are appreciated.