如何将两种泛型类型传递给扩展方法 [英] How to pass two 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, it's more a fact finding mission.
更新
For those of you playing at home, with the help of Scott's comment I managed to find an additional solution 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));
}
推荐答案
如果您想知道为什么为什么这是不可能的,我想问题在于模棱两可:
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.
这篇关于如何将两种泛型类型传递给扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!