使用Func <>创建递归方法助手

问题描述 投票:1回答:1

我有两个带有签名的方法助手:

@helper CreateNavigation(int parentId,int depthNavigation)

@helper Navigation(int parentId,int depthNavigation)

我试图将其转换为在ASP.NET Core 2中使用的正确方法。

但我在VS2017 IDE中遇到一个错误:

1-使用未分配的局部变量'导航' 在访问之前,可能无法初始化2-局部变量“Navigation”

我该如何解决?

@using Microsoft.AspNetCore.Html
@using Microsoft.AspNetCore.Mvc.Razor
@model List<Jahan.Beta.Web.App.Models.Comment>

@{
    Func<int, int, int, HelperResult> CreateNavigation
        = (parentId, depthNavigation) => new Func<object, HelperResult>(
    @<text>@{
                Comment parent = Model.SingleOrDefault(r => r.Id == parentId);
                depthNavigation = 6;
        @Navigation(parentId, depthNavigation)
    }</text>)(null);
}
@{

    Func<int, int, HelperResult> Navigation
        = (parentId, depthNavigation) => new Func<object, HelperResult>(
    @<text>@{
                var parent = Model.Children(parentId);
                if (//condition)
                {
                    if (//condition)
                    {
                        foreach (var comment in Model)
                        {
                            if (//condition)
                            {
                                <li><p>@comment.Description</p></li>
                                @Navigation(comment.Id, depthNavigation)
                            }
                        }
                    }
                }
    }</text>)(null);
}
razor asp.net-core html-helper asp.net-core-2.0
1个回答
1
投票

我有同样的问题,我能够通过首先声明委托并将其设置为null来解决它,然后添加如下的实现:

@{Func<IEnumerable<Foo>, IHtmlContent> DisplayTree = null;}
@{DisplayTree = @<text>@{
  var foos = item;
  <ul>
  @foreach (var foo in foos)
  {
  <li>
    @foo.Title
    @if (foo.Children.Any())
    {
      @DisplayTree(foo.Children)
    }
  </li>
  }
  </ul>
}</text>;}


@DisplayTree(new List<Foo>{...})
© www.soinside.com 2019 - 2024. All rights reserved.