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

Yos*_*srJ 2 c# asp.net asp.net-mvc static-methods

我创建了一个使用名为 GetUrl 的方法的部分视图,但出现错误cannot access static method in a non static context。

以下是我如何实现该方法:

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 "#";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的部分观点:

@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>
}
Run Code Online (Sandbox Code Playgroud)

该部分视图生成一个带有 URL 的垂直菜单。我如何调用我的静态方法?

Jam*_*iec 5

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

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

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

public string GetUrl()
{
    switch (this.Code)
         ....
Run Code Online (Sandbox Code Playgroud)

然后将被称为

<a href="@menuItem.GetUrl()"> @menuItem.Title </a>
Run Code Online (Sandbox Code Playgroud)