【问题标题】:cannot implicitly convert type List<Foo> to system.collections.generic.list<T>无法将类型 List<Foo> 隐式转换为 system.collections.generic.list<T>
【发布时间】:2017-09-19 18:36:38
【问题描述】:

我觉得我真的应该知道这个问题的答案……哈哈!!

为什么在泛型列表的函数中返回类型列表会引发编译错误?

示例代码:

public List<T> Method<T>() where T : new()
{
   var items = new List<Foo>();

   return items;
}

【问题讨论】:

  • 应该是:var items = new List()
  • 因为没有什么可以保证 Foo 可以转换为 T。
  • @Trioj 即使可以,它仍然行不通。
  • @sTrenat - 出于同样的原因,这仍然行不通。
  • 这只是代码中某处的问题还是实际问题?如果你想返回Foo,那么不要使用泛型返回类型。

标签: c# .net generics collections


【解决方案1】:

如果你把你的函数称为:

List<Bar> items = Method<Bar>();

这是行不通的,因为你的方法会给你一个 foo 列表。

不使用泛型的另一种方法是返回接口列表。

public List<iFoo> Method()
{
   var items = new List<Foo>();

   return items;
}

【讨论】:

  • 列表不支持协方差。没有任何类型的课程。
  • List&lt;T&gt; 是不变的,因此您不能将List&lt;Foo&gt; 分配给List&lt;IFoo&gt;
【解决方案2】:
public interface IFoo
{
    int getAll();
}
public class Foo : IFoo
{
    public Foo()
    {
    }
    public int getAll() => 1;
}

public List<T> Method<T>() where T : IFoo, new()
{
   var items = new List<T>();

   var foo = new T();
   items.Add(foo);
   return items;
}
var list = Method<Foo>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多