How to pass 2 generics types into an extension method [duplicate]

狂风中的少年 提交于 2019-11-29 13:56:23

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.

What you're asking for is not possible. When you call a generic method, either all generic type parameters must be inferable from the input or you must specify them all explicitly. Your method only has one input so you can't possibly infer two generic type parameters, thus they must always both be specified explicitly. Your suggested code implies that the method has only one generic type parameter, which would make it a different method.

If you introduce a second (chained) function call, you can achieve this:

Db.ExchangeSets.FirstOrDefault().Map().To<ExchangeSetSimpleViewModel>()

Inferred generic parameters is an all-or-nothing deal; if there aren't enough "actual" parameters passed into the method for the compiler to figure out the all of generic parameters, the compiler forces you to specify each generic parameters manually.

To be able to use the above snippet, you need to have one method call with one (the only) generic parameter inferred, and one method call with one manually specified generic parameter.

The To<> method can be implemented like this:

public static MapExtensionHelper<TEntity> Map<TEntity>(this TEntity entity) where TEntity : IEntity
{
    return new MapExtensionHelper<TEntity>(entity);        
}

public class MapExtensionHelper<TEntity> where TEntity : IEntity
{
    public MapExtensionHelper(TEntity entity)
    {
        _entity = entity;
    }

    private readonly TEntity _entity;

    public T To<T>()
    {
        return Mapper.Map<TEntity, T>(_entity);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!