Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'?

二次信任 提交于 2020-12-26 07:51:46

问题


I'm pretty new to C# and I'm getting an error I can't quite figure out?

I have a view where I want to loop a series of nodes, so I'm trying do to this:

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

As in my viewmodel I have this:

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:


Model.Breadcurmb is a method and not a property or field, so call it as below

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



回答2:


When you don't add parentheses compiler treats the method as method group. If you want to call the method and iterate over the result then use:

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


来源:https://stackoverflow.com/questions/28693212/foreach-cannot-operate-on-a-method-group-did-you-intend-to-invoke-the-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!