.NET Core Razor C#函数

5

我对.NET Core(尤其是ASP.NET)还比较陌生,想知道在视图中创建C#函数时是否有明显的错误。

我的视图如下(Collections.cshtml):

<h2>Collections</h2>

<div id="content">

    @{
        // define variables
        List<string> collections;
        int counter;

        // build list
        collections = new List<string>();
        collections.Add("Nothing 01");
        collections.Add("Nothing 02");

        // display list
        counter = 0;
        while(counter < collections.Count)
        {
            <p>@collections[counter]</p>
            counter = counter + 1;
        }
    }

</div>

这一切都很正常,也实现了我想要的功能,但是如果我尝试将其组织成函数或甚至添加基本函数,它会像下面一样崩溃。

@{
    // function for no reason
    public void testFunc()
    {
        string nothing;
        nothing = null;
        return;
    }
}

<h2>Collections</h2>

<div id="content">

    @{
        // define variables
        List<string> collections;
        int counter;

        // build list
        collections = new List<string>();
        collections.Add("Nothing 01");
        collections.Add("Nothing 02");

        // display list
        counter = 0;
        while(counter < collections.Count)
        {
            <p>@collections[counter]</p>
            counter = counter + 1;
        }
    }

</div>

只是添加那个功能会导致出错,我不确定原因。


3
“it breaks”并没有告诉我们你遇到了什么错误。 - Jon Skeet
下面的所有旧代码都开始说变量未声明,当我运行页面时,它显示了一堆错误,比如“} 期望”、“标识符期望”和“类型期望”,至少有50行错误。 - TheLovelySausage
请编辑问题并显示一个最小但完整的示例(其中包括所有错误消息)以展示您的问题。我知道这个问题现在已经被回答和关闭,但现在改进它也不迟。 - Jon Skeet
这个问题确实是一个重复的问题,但我没有意识到 Razor 有一种特定的定义函数的方式,这并不是标准 C#。请问是否可以关闭这个问题,因为我认为它对任何人都没有用处。 - TheLovelySausage
1个回答

11

它们放在@functions部分,您不需要添加可访问性修饰符:

@functions {
    // function for no reason
    void testFunc()
    {
        string nothing;
        nothing = null;
        return;
    }
}

这太完美了,非常感谢。我之前不知道我需要一个特定的部分。 - TheLovelySausage
我只是在等计时器,这样我就可以接受它了。 - TheLovelySausage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接