c# - 当返回类型已知时,泛型方法的“方法的类型参数无法从用法中推断”错误
问题描述
这个小例子会导致编译错误:
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我确实知道如何显式指定类型,我只是想找出是否有办法让编译器自己发现这一点,或者这就是编译器的设计方式
解决方案
推荐阅读
- docker - 为多台机器执行对等链码查询时未能获取 mycc:1.0 的链码容器信息
- node.js - 如何将账单添加到 Shopify 节点和 Express 应用程序
- json - 如何在虚幻引擎中使用 FJsonSerializer::Deserialize() 反序列化 JSON?
- sql-server - 将 CSV 导入 SQL 失败
- r - 在ggplot中标记起点和终点
- java - 如何将pdf文件按一页拆分并删除未使用的对象(优化)
- r - 有没有一种优雅的方法来估计一种正态分布向量的截止值?
- firebase - Firebase 消息传递,无法确定消息传递的项目 ID
- ios - 来电的 CallKit UI 上未显示应用程序图标
- html - 有没有办法限制导航子菜单弹性框中每行的项目数量?