c# - 无法在非静态上下文中访问静态方法

标签 c# asp.net asp.net-mvc static-methods

我创建了一个使用名为 GetUrl 的方法的分部 View ,但收到错误无法在非静态上下文中访问静态方法

这是我实现该方法的方法:

public class TimeLineStep
{
    public string Code { get; set; }
    public string Title { get; set; }
    public TimeLineStatus Status { get; set; }
    public string Description { get; set; }
    public string Category { get; set; }

    public static string GetUrl(string code)
    {
        switch (code)
        {
            case "1":
                return "#";
            case "2":
                return "#";
            case "3":
                return "#";
            case "4":
                return "#";
            case "5":
                return "#";
            case "6":
                return "#";
            case "7":
                return "#";
            default:
                return "#";
        }
    }
}

以及我的部分观点:

@using UI.Controls
@model List<Web.Models.TimeLineStep>
@{
    Layout = null;
}
@using (Html.ContentBlock("Yellow", ""))
{
    <ul>
        @foreach (var menuItem in Model)
        {
            <li>
                <a href="@menuItem.GetUrl(menuItem.Code)"> @menuItem.Title </a>
            </li>
        }
    </ul>
}

此部分 View 生成带有 URL 的垂直菜单。如何调用我的静态方法?

最佳答案

您调用类本身的静态方法,而不是类的实例。

<a href="@TimeLineStep.GetUrl(menuItem.Code)"> @menuItem.Title </a>

但是你确定要使其静态吗?看来您想要的是:

public string GetUrl()
{
    switch (this.Code)
         ....

这将被称为

<a href="@menuItem.GetUrl()"> @menuItem.Title </a>

关于c# - 无法在非静态上下文中访问静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725065/

相关文章:

c# - 通过 C# 或 appcmd 编辑绑定(bind) IIS 8

c# - 参数字典包含不可为 null 类型 'id' 的参数 'System.Int32' 的 null 条目

c# - 将父模型的一个元素传递给局部 View

javascript - 移动 'back' 按下后运行 javascript

c# - 如何将二进制文件头示例代码(C++/C#)转换为Python?

c# - 我可以在 MVC 站点下的虚拟目录中拥有传统的 ASP.NET Web 应用程序吗?

c# - 替代 INotifyCollectionChanged

c# - 读取数组或列表中的 SQL Server 列

javascript - 无法使用systemjs构建Angular 4项目

c# - ASP.NET Web APi - 将对象作为参数传递