如何通过2种仿制药进入一个扩展方法 [英] How to pass 2 generics types into an extension method
问题描述
我创建了下面的扩展方法
I've created the following extension method
public static T Map<TEntity,T>(this TEntity entity) where TEntity : IEntity
{
return Mapper.Map<TEntity, T>(entity);
}
这允许以下
Db.ExchangeSets.FirstOrDefault().Map<ExchangeSet, ExchangeSetSimpleViewModel>()
不过,我想知道是否有反正我可以修改扩展方法,所以我可以调用一个缩如下:
However i'm wondering if there is anyway i can modify the extension method so i can call a shorted version as follows
Db.ExchangeSets.FirstOrDefault().Map<ExchangeSetSimpleViewModel>()
请注意:
不管是不是automapper应该使用这样是不是在问题的范围,其更多的事实调查团
Whether or not automapper should be used like this is not in the scope of the question, its more a fact finding mission
的更新
对于那些你在家里玩与斯科特的帮助评论我设法找到的对于automapper
For those of you playing at home, with the help of scotts comment i managed to find an additional solve for the above function at Generic extension method for automapper
public static T Map<T>(this IEntity entity)
{
return (T)Mapper.Map(entity, entity.GetType(), typeof(T));
}
不过AutoMapper不谈,这是没有答案的实际问题,将标志择优因此
However AutoMapper aside, this is not the answer to the actual question and will mark on merit accordingly
推荐答案
在如果你想知道的为什么的这仅仅是不可能的,我会认为问题在于歧义:
In case you are wondering why this is just not possible, I'd think the problem lies with ambiguity:
public static T Map<TEntity,T>(this TEntity entity) where TEntity : IEntity
{
return Mapper.Map<TEntity, T>(entity);
}
public static T Map<T>(this ExchangeSet set)
{
// ...
}
那么,哪种方法被调用?请记住,这仅仅是一个简单的例子。这是非常可能,有可能是未来局部类型推断的实现,但我想这将是太混乱,当谈到超载分辨率和成本/收益会完全失控。话又说回来,这只是猜测。
So, which method gets called? Keep in mind this is just a simple example. It's very well possible that there could be a future implementation of partial type inference, but I'd imagine it would be too confusing when it comes to overload resolution and the cost/benefit would be completely out of control. Then again, that's just speculation.
这篇关于如何通过2种仿制药进入一个扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!