我有一个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(我猜这是我们允许的性能截止)。怎么办呢?
答案 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);
}
}