代码之家  ›  专栏  ›  技术社区  ›  Gacek

嵌套泛型类型参数-如何处理?

  •  2
  • Gacek  · 技术社区  · 16 年前

    public void Foo(IList<Pair<double, IList<double>>> myParameter)
    { // code goes here 
    }
    

    • List<Pair<double, List<double>>> myVar
    • List<Pair<double, double[]>> myVar
    • Pair<double, List<double>>[] myVar
    • Pair<double, double[]>[] myVar

    但第二,嵌套接口似乎不能通过C#进行动态转换。在尝试将上面列出的一些变量传递给我的方法时,出现错误:

    我真的需要为这个方法创建两个别名来处理这个问题吗?或者我可以用某种技巧来克服这个问题?

    3 回复  |  直到 16 年前
        1
  •  5
  •   Dario    16 年前

    您的代码导致了差异问题。

    内在的 IList<double> 允许您分配 List<double> double[]

    (发生这种情况的原因与 List<Orange> 可能不会被视为 List<Fruit> :你可以把苹果推进去。)

    为了实现正确的差异行为,您必须通过使用 IEnumerable<T> s而不是 IList<T>

        2
  •  2
  •   Robert Davis    16 年前

    您可以在C#2.0中使用泛型约束+

    void Foo<TList>(IList<Pair<double, TList>> myParameter)
       where TList : IList<double>
    

        3
  •  1
  •   casperOne    16 年前

    在不知道你在传递什么的情况下,这里的问题很可能是因为你没有 variance on generic type parameters

    IEnumerable<double>

    List<T> 变量设置为请求的特定类型。