需要将类型参数化的方法用于存储库的实现

时间:2014-04-30 18:18:16

标签: c#

我有一个Repository类:

public class Repository<T> where T : IMappable
{
     public virtual List<IMappable> Get()
     {
          return new DataProvider().Get(/* somehow use T's Map() method */);
     }
}

internal class DataProvider
{
     public delegate IMappable Mapper(Object dataSource);
     public List<IMappable> Get(Mapper mapper)
     {
          List<IMappable> mappables = new List<IMappable>();
          //Paraphrasing
          foreach(var ds in dataSource)
          {
              mappables.Add(mapper(ds));
          }
          return mappables;
     }
}

public interface IMappable
{
     IMappable Map(Object dataSource);
}

当我创建Repository<TypeThatImplementsIMappable>时,我想传递它以使用泛型类型的Map方法。出于性能原因,我不能使用反射或代码DOM(我猜这是我们允许的性能截止)。怎么办呢?

1 个答案:

答案 0 :(得分:1)

您可以向new添加T约束:

public class Repository<T> where T : IMappable, new()
{
     public virtual List<IMappable> Get()
     {
          T mapper = new T();
          return new DataProvider().Get(mapper.Map);
     }
}