是否可以在不在表达式中指定的情况下将任务类型推断为通用类型?

Is it possible to infer the type of a task as generic type, without specifying it in an expression?

我正尝试在我正在处理的包装器上提供一个不错的 API,并且我 运行 遇到了以下问题:

这是我的沙盒代码:

public interface ISomeInterface
{
    Task<int> SomeMethod(int i);
    Task<Task<int>> SomeOtherMethod(int i);
}

public class TestClass<TSource>
{
    public TWrap ReturnExpressionAsIs<TWrap>(Expression<Func<TSource, TWrap>> expression)
    {
        return default(TWrap);
    }

    public TImplicit SomeExpressionFromTask<TWrap, TImplicit>(Expression<Func<TSource, TWrap>> expression) where TWrap : Task<TImplicit>
    {
        return default(TImplicit);
    }
}

我正在使用这样的代码:

var testProxy = new TestClass<ISomeInterface>();
// Task<int> - working as intended
var ordinaryTypeInfer = testProxy.ReturnExpressionAsIs(d => d.SomeMethod(5));

// int - working as intended
var expressionExplicit = testProxy.SomeExpressionFromTask<Task<int>, int>(d => d.SomeMethod(5));

// compiler error - shouldn't this be possible through type inference?
var expressionImplicitAttempt = testProxy.SomeExpressionFromTask(d => d.SomeMethod(5));

基本上我希望 TImplicit 对于 SomeMethod 是 int,对于 SomeOtherMethod 是可选的 Task(但是,如果可选的不可能,那对我来说非常有意义)。

不,不是真的。

但是,你把事情搞得太复杂了。而不是 TWrap: Task<TImplicit>,直接使用 Task 即可:

public TImplicit SomeExpressionFromTask<TSource, TImplicit>
       (Expression<Func<TSource, Task<TImplicit>>> expression)
{
    return default(TImplicit);
}

如果您无法简化泛型类型参数和约束,则为类型推断添加虚拟参数可能是有意义的:

public V DoStuff<T, U, V>(Func<T, U> func, V dummy) where U: A<V> { ... }

这允许您调用

DoStuff(i => SomeFun(i), default(int));

当然,这实际上只是一个辅助方法 - 在您的核心实现中这样做没有意义。