首页 > 解决方案 > 当返回类型已知时,泛型方法的“方法的类型参数无法从用法中推断”错误

问题描述

这个小例子会导致编译错误:

public static class TestClass
{
    public static T Create<T>() where T : new()
    {
        return new T();
    }

    public static void Foo()
    {
        // The type arguments for method 'T TestClass.Create<T>()' cannot be inferred 
        // from the usage. Try specifying the type arguments explicitly.
        HttpClient client = Create(); 
    }
}

这是类型推断应该如何工作的吗?从我所看到的情况来看,在这种情况下T应该是相当明显的,HttpClient因此我不需要明确指定它。

但也许推理不适用于设计的返回类型?

PS我确实知道如何显式指定类型,我只是想找出是否有办法让编译器自己发现这一点,或者这就是编译器的设计方式

标签: c#genericstype-inference

解决方案


推荐阅读