【问题标题】:Cannot initialize type x with a collection initializer because it does not implement 'System.Collections.IEnumerable'无法使用集合初始化程序初始化类型 x,因为它没有实现“System.Collections.IEnumerable”
【发布时间】:2015-04-20 04:26:44
【问题描述】:

我正在证明此代码,但它向我发送了有关集合初始化的错误。

无法使用集合初始化器初始化类型 x,因为它没有实现 'System.Collections.IEnumerable'

我正在尝试使用 MVC 5

private readonly List clients = new List()
   {
        new Pruebas.Models.Client { Id = 1, Name = "Julio Avellaneda", Email = "julito_gtu@hotmail.com" },
        new Pruebas.Models.Client { Id = 2, Name = "Juan Torres", Email = "jtorres@hotmail.com" },
        new Pruebas.Models.Client { Id = 3, Name = "Oscar Camacho", Email = "oscar@hotmail.com" },
        new Pruebas.Models.Client { Id = 4, Name = "Gina Urrego", Email = "ginna@hotmail.com" },
        new Pruebas.Models.Client { Id = 5, Name = "Nathalia Ramirez", Email = "natha@hotmail.com" },
        new Pruebas.Models.Client { Id = 6, Name = "Raul Rodriguez", Email = "rodriguez.raul@hotmail.com" },
        new Pruebas.Models.Client { Id = 7, Name = "Johana Espitia", Email = "johana_espitia@hotmail.com" }

    };

我的班级列表

class List
{

}

【问题讨论】:

  • 为什么你有自己的自定义List 类?为什么不使用内置类List
  • 这个错误似乎很合适。您的“列表”类不是 IEnumerable。 List 似乎只是一个名为 List 的空类。也许你的意思是使用 List,例如:private readonly List clients = new List()
  • 这些看起来像真实的电子邮件地址。你确定他们应该在那里吗?

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

我认为您需要使用 System.Collections.Generic 中的 List<T> 而不是创建自己的 List 类。您的列表类只是一个空类。为了实现您正在做的事情,请删除您的列表类,导入命名空间System.Collections.Generic 并使用List<T>

这是您使用 List 的代码

删除您的 List 类。

然后像这样导入 System.Collections.Generic 命名空间。

Using System.Collections.Generic;

然后使用下面的代码。

private readonly List<Pruebas.Models.Client> clients = new List<Pruebas.Models.Client>()
{
        new Pruebas.Models.Client { Id = 1, Name = "Julio Avellaneda", Email = "julito_gtu@hotmail.com" },
        new Pruebas.Models.Client { Id = 2, Name = "Juan Torres", Email = "jtorres@hotmail.com" },
        new Pruebas.Models.Client { Id = 3, Name = "Oscar Camacho", Email = "oscar@hotmail.com" },
        new Pruebas.Models.Client { Id = 4, Name = "Gina Urrego", Email = "ginna@hotmail.com" },
        new Pruebas.Models.Client { Id = 5, Name = "Nathalia Ramirez", Email = "natha@hotmail.com" },
        new Pruebas.Models.Client { Id = 6, Name = "Raul Rodriguez", Email = "rodriguez.raul@hotmail.com" },
        new Pruebas.Models.Client { Id = 7, Name = "Johana Espitia", Email = "johana_espitia@hotmail.com" }

};

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多