c# - 当使用带有IEnumerable值的Dictionary时,无法从用法中推断出方法的类型参数

标签 c# generics

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/

相关文章:

c# - 运行除 [Authorize] 注释之外的其他逻辑

c# - 删除记录的重复项但保留 1(不带标识符)

c# - 许多自定义用户控件实现相同的界面;有没有办法避免在每个代码中重复相同的代码?

c# - 是否可以将json参数作为请求数据发送到webservice并获得xml格式的回复

java - 如何将有界泛型扩展为另一个有界泛型?

java - 是否可以在java中编写一个递归方法,其中列表中的所有项目都被最后一个元素替换?(不使用循环)

c# - 在代码中创建时的 UITableView 工件

java - Collections.emptyList() 之谜

c# - 构造通用对象(不是默认构造函数)

vb.net - 限制列表(Of T)的大小 - VB.NET