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

我创建了一个包含三个类作为属性的类:

public class Feeds
{
    public Rentals Rentals { get; set; }
    public Agent Agents { get; set; }
    public NorthwindService.ServiceReference1.File File { get; set; }
}

我是这样使用它的:

var query = from r in ent.Rentals
            join a in ent.Agents on r.ListingAgentID equals a.AgentID
            select new Feeds
            {
                a.AgentID,
                a.Alias,
                a.Bio,
                a.Email,
                a.Fax,
                r.Firstname,
                r.IsStaff,
                r.Languages
            };

但我收到了错误:

无法使用集合初始化程序初始化类型“NorthwindService.WebForm1.Feeds”,因为它没有实现“System.Collections.IEnumerable”C:\Users\NorthwindService\NorthwindService\WebForm1.aspx.cs

请提出解决方案。

【问题讨论】:

  • 您的 select 子句没有任何意义。你认为它有什么作用?
  • @SLaks 我想从代理中选择一些字段,从租赁中选择一些字段,这就是我创建 Feed 并尝试填充它的原因

标签: c# asp.net linq


【解决方案1】:

您在这里使用 C# 中的集合初始化程序:

new myClass{a,b,c} 

其中 myClass 是一个集合,a,b,c 将被插入到这个集合中。

但是,您需要使用的符号是对象初始化器:

new myClass{
   myProperty1 = a,
   myProperty2 = b,
   myProperty3 = c
}

myClass 的成员将被初始化的地方。或者您可能需要使用经典构造函数,然后用括号更改括号:

new myClass(a,b,c)

【讨论】:

  • 我认为 DotnetSparrow 实际上是在尝试使用对象初始化器,但是在匿名类型的语法中,它将从源属性的名称中推断出名称。当您指定类型时,这是无效的。在这种情况下,您还必须指定属性名称。
  • 不确定这个答案是否适用于这个问题,但它是我的问题的解决方案。
  • 这个答案拯救了我的一天。我试图初始化新的 KeyValuePair,就像我们做 Dictionary.
  • 我遇到了同样的问题,您的回答设法解决了它。谢谢!
【解决方案2】:

应该是:

var query = from r in ent.Rentals
           join a in ent.Agents on r.ListingAgentID equals a.AgentID
           select new Feeds
           {
                    Agents = a,
                    Rentals = r
           }

【讨论】:

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