Type inference problem when writing a generic extension method with more than one type

点点圈 提交于 2019-12-05 08:28:36

The problem is that the type inference for T1 doesn't work

Actually, the problem isn't T1 - it is T2; return types are not used in this inference. So you can't do that. One option might be a fluent API, for example:

return articles.Map(_mappingEngine).To<SomeT2>();

with something like:

public static MapProjection<T1> Map<T1>(this IEnumerable<T1> list, IMappingEngine engine)
{
    return new MapProjection<T1>(list, engine);
}
public class MapProjection<T1>
{
    private readonly IEnumerable<T1> list;
    private readonly IMappingEngine engine;
    internal MapProjection( IEnumerable<T1> list, IMappingEngine engine)
    {this.list = list; this.engine = engine;}

    public IEnumerable<T2> To<T2>()
    {
        return list.Select(engine.Map<T1, T2>());
    }
}

assuming that the interface is something like:

public interface IMappingEngine {
    Func<T1, T2> Map<T1, T2>();
}

I believe you want C# compiler to infer type of T1 even if you provide T2 without providing T1.

The point is you can use type inference, or just don't use it. You can't mix both worlds:

    public void M<T, S>(T t, S s)
    {
    }

    M<string>("hello", "world!")

This code doesn't compile, but:

    public void M<T, S>(T t, S s)
    {
    }

    M("hello", "world!")

..compiles.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!