使用Func创建递归方法助手. [英] Creating recursive method helper with Func<>
问题描述
我有两个带有这些签名的方法助手:
I have two method helper with theses signatures:
@helper CreateNavigation(int parentId,int depthNavigation)
@helper CreateNavigation(int parentId, int depthNavigation)
@helper导航(int parentId,int depthNavigation)
@helper Navigation(int parentId, int depthNavigation)
我试图将其转换为在ASP.NET Core 2
中使用的正确方法.
I have tried to convert it to a proper method for using in ASP.NET Core 2
.
但是我在VS2017 IDE
中遇到了一个错误:
But I got an error in VS2017 IDE
that is:
1-使用未分配的局部变量"Navigation"
2-局部变量 访问前可能未初始化导航"
1- Use of unassigned local variable 'Navigation'
2- local variable 'Navigation' might not be initialized before accessing
我该如何解决?
@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,然后添加如下实现来解决此问题:
I had the same problem and I was able to solve it by declaring the delegate first and setting it to null, then adding the implementation like this:
@{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>{...})
这篇关于使用Func创建递归方法助手.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!