问题
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