1

假设我的数据访问层中有以下类结构:

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.

4

2 回答 2

1

Not sure if this would work in your exact context, but have you tried making ApplyFolders generic itself?

void ApplyFolders<TEnum>(ref IEnumerable<TEnum> models) where TEnum : T;
于 2011-01-06T15:14:34.183 回答
1

I would take a look at the Ptr class. I've been taking advantage of this class recently to completely bust all of the limitations .NET puts on ref keywords to let me side effect objects the CLR for some reason feels I have no right to.

于 2011-01-06T15:24:43.137 回答