2015-02-24 104 views
1

我对C#很新,我收到一个错误,我无法弄清楚吗?Foreach无法在'方法组'上操作。你打算调用'方法组'吗?

我有我想要的循环一系列节点的看法,所以我试图做这样的:

@foreach (var crumb in Model.Breadcrumb) 
{ 
    //My code 
} 

正如我的ViewModel我有这样的:

public IEnumerable<LinkModel> Breadcrumb(IPublishedContent content) { 
    //Do logic. 
    return GetFrontpage(content, true).Reverse().Select(item => new LinkModel { 
     Target = "", 
     Text = item.Name, 
     Url = item.Url 
    }); 
} 

private static IEnumerable<IPublishedContent> GetFrontpage(IPublishedContent content, bool includeFrontpage = false) 
{ 
    var path = new List<IPublishedContent>(); 

    while (content.DocumentTypeAlias != "frontpage") 
    { 
     if (content == null) 
     { 
      throw new Exception("No frontpage found"); 
     } 
     path.Add(content); 
     content = content.Parent; 
    } 
    if (includeFrontpage) 
    { 
     path.Add(content); 
    } 
    return path; 
} 
+1

它指向哪条线在编译错误? – Dreamwalker 2015-02-24 10:27:35

回答

3

Model.Breadcurmb是一种方法,而不是一个属性或字段,所以称其为以下

 @foreach (var crumb in Model.Breadcrumb(content)) 
6

当您不要添加括号,编译器会将该方法视为method group。如果你要调用的方法,并遍历结果,那么使用:

@foreach (var crumb in Model.Breadcrumb(/* your parameters */)) 
+0

在你的模型中为名称和列表渲染成foreach – 2015-02-24 10:27:21