[英]Open generic type arguments cannot be inferred from the usage
在这个问题中,当提到编译器时,我实际上指的是Roslyn编译器。 使用IntelliSense时出现问题, IntelliSense被认为是相同的编译器。
出于演示目的和完整性,使用以下类( 使用Visual Studio 2015与C#6.0和.NET 4.6.1 ):
public class A
{
public IEnumerable<B> B { get; set; }
}
public class B
{
public IEnumerable<C> C { get; set; }
}
public class C { }
public class Helper<T> { }
请看以下扩展方法:
public static void FooBar<T1, T2>(
this Helper<IEnumerable<T1>> helper,
Expression<Func<T1, IEnumerable<T2>>> expression) { ... }
编译器能够在消耗时推断它,如下所示:
Helper<IEnumerable<B>> helper = ...;
helper.FooBar(l => l.C); //T1 is B and T2 is C
还有这个重载的扩展方法:
public static void FooBar<T1, T2, T3>(
this Helper<T1> helper,
Expression<Func<T1, IEnumerable<T2>>> expression1,
Expression<Func<T2, IEnumerable<T3>>> expression2) { ... }
编译器不能推断T1
像这样,只要当它:
Helper<A> helper = ...;
helper.FooBar(l => l. //compiler/IntelliSense cannot infer that T1 is A
当我用鼠标悬停在扩展方法上时,我收到此错误消息( 我已经分别用[
和]
替换了<
和>
字符,因为StackOverflow无法格式化报价中的那些 ):
方法'FooBar [T1,T2](此Helper [IEnumerable [T1]],Expression [Func [T1,IEnumerable [T2]]])'的类型参数不能从用法中推断出来。 尝试显式指定类型参数。
但是当像这样手动完成它时:
helper.FooBar(l => l.B, l => l.C); //compiler infers that T1 is A, T2 is B and T3 is C
编译器很高兴。
为什么编译器/ IntelliSense( 或Visual Studio的自动完成功能 )无法找出T1
并希望我在开始输入时明确指定类型参数?
请注意 ,如果我在示例中省略了IEnumerable<>
,编译器可以在键入时愉快地推断出所有内容。
手动输入l => lB
后,编译器也很高兴。 然后它知道T1
是A
,所以你可以表达与智能感知的帮助下,最后一个参数。
我发现你的问题很有趣,因为我正在使用VS 2015,我想我也可以尝试一下。 我得到了和你一样的错误,所以我猜它可能是一个VS bug,因为在其他版本中它运行正常。
这是我的错误:
我也对CTRL + SPACE 没有任何建议 。
编辑:
这里可以看到类似的错误。
所以,因为在旧版本的VS中,这是有效的,所以这就是它被认为是一个bug的原因。
正如我所说,我有同样的问题。 ( 这是错误报告)
它与Expressions或IEnumerable无关。
这是一个简化的例子
using System;
namespace ConsoleApplicationExpressionTree
{
public static class Extentions
{
static void Main() { }
static void AMethod(string[] args)
{
SetValue(new Customer(), e => e.Name /*type here */, "TheName");
}
public static void SetValue<TEntity, TProperty>(TEntity instance, Func<TEntity, TProperty> expression, TProperty newValue)
{
}
}
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
}
我刚刚注意到,如果从方法中删除第三个参数,它就可以了!
using System;
namespace ConsoleApplicationExpressionTree
{
public static class Extentions
{
static void Main() { }
static void AMethod(string[] args)
{
SetValue(new Customer(), e => e.Name /*type here */);
}
public static void SetValue<TEntity, TProperty>(TEntity instance, Func<TEntity, TProperty> expression)
{
}
}
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
}
因此,如果您非常幸运,您可以通过调整参数来修复当前示例。
如果没有,你只需要等待MS修复它......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.