using System;
using System.Collections.Generic;
public class Test
{
static List<T> F<T>(IDictionary<int, IEnumerable<T>> dictionary)
{
// ...
return new List<T>();
// ...
}
public static void Main()
{
var mydict = new Dictionary<int, LinkedList<int>>();
F(mydict);
}
}
running the code之后的错误消息:
prog.cs(16,3): error CS0411: The type arguments for method `Test.F<T>(System.Collections.Generic.IDictionary<int,System.Collections.Generic.IEnumerable<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly
Compilation failed: 1 error(s), 0 warnings
最佳答案
Dictionary<int, LinkedList<int>>
不是Dictionary<int, IEnumerable<int>
。
您将需要使用如下签名:
static List<T> F<T, U>(IDictionary<int, U> dictionary) where U : IEnumerable<T>
这样您就可以传递一个参数,该参数是一个字典,其键类型为
int
,而值类型是一种实现IEnumerable<T>
的类型,但本身(不一定)不是IEnumerable<T>
的类型。不幸的是,该类型仍然不能被推断,因此必须使用以下命令进行调用:
F<int, LinkedList<int>>(mydict);
关于c# - 当使用带有IEnumerable值的Dictionary时,无法从用法中推断出方法的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34587916/