使用多种类型编写通用扩展方法时,输入推理问题 [英] Type inference problem when writing a generic extension method with more than one type

查看:150
本文介绍了使用多种类型编写通用扩展方法时,输入推理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为IEnumerable编写一个通用扩展方法,用于将对象列表映射到另一个映射对象列表。这是我希望这种方法起作用的方式:

I am writing a generic extension method for IEnumerable for mapping a list of objects to another list of mapped objects. This is how I would like the method to work:

IList<Article> articles = GetArticles();
return articles.Map<ArticleViewModel>(_mappingEngine);

这是方法:

This is the method:

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

然而 articles.Map< ArticleViewModel>(_ mappingEngine) ; 给出一个编译错误。
问题是T1的类型推断不起作用。

However articles.Map<ArticleViewModel>(_mappingEngine); gives a compile error. The problem is that the type inference for T1 doesn't work. I have to explicitly call it like this instead:

articles.Map<Article, ArticleViewModel>(_mappingEngine);

如果我创建一个只有一个参数T1的扩展方法,如下所示:

If I create an extension method with only one parameter T1 like this:

public static IEnumerable<T1> DummyMap<T1>(this IEnumerable<T1> list, IMappingEngine engine)
{
    return list;
}

然后我可以像这样调用它,而不必指定T1: p>

Then I can call it like this, without having to specify T1:

articles.DummyMap(_mappingEngine);

是否有理由说编译器无法在Map的扩展方法中推断出T1的类型?

Is there are reason why the compiler can't infer the type of T1 in the extension method for Map?

推荐答案


问题是T1的类型推断不起作用

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

实际上,问题不是T1 - 它是T2;返回类型不用于此推断。所以你不能那样做。例如:一个选项可能是流畅的API,例如:

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>());
    }
}

假设接口类似于:

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

这篇关于使用多种类型编写通用扩展方法时,输入推理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆