【问题标题】:Creating recursive method helper with Func<>使用 Func<> 创建递归方法助手
【发布时间】:2018-06-21 00:25:27
【问题描述】:

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

@helper CreateNavigation(int parentId, int depthNavigation)

@helper Navigation(int parentId, int depthNavigation)

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

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

1- 使用未分配的局部变量“导航”
2-局部变量 访问前可能未初始化“导航”

我该如何解决?

@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);
}

【问题讨论】:

  • 声明你的变量之前然后声明方法然后用null初始化

标签: razor asp.net-core html-helper asp.net-core-2.0


【解决方案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>{...})

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 2011-06-04
    • 1970-01-01
    • 2021-04-23
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 1970-01-01
    相关资源
    最近更新 更多