How do you write a C# Extension Method for a Gener

2019-01-24 09:25发布

This should hopefully be a simple one.

I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.

How should this extension method look?

My first intuitive thought is something like this:

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle(this ViewPage<Type> v)
        {
            return "";
        }
    }
}

Solution

The general solution is this answer.

The specific solution to extending the System.Web.Mvc.ViewPage class is my answer below, which started from the general solution.

The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.

7条回答
叼着烟拽天下
2楼-- · 2019-01-24 10:02

Here's an example for Razor views:

public static class WebViewPageExtensions
{
    public static string GetFormActionUrl(this WebViewPage view)
    {
        return string.Format("/{0}/{1}/{2}", view.GetController(), view.GetAction(), view.GetId());
    }

    public static string GetController(this WebViewPage view)
    {
        return Get(view, "controller");
    }

    public static string GetAction(this WebViewPage view)
    {
        return Get(view, "action");
    }

    public static string GetId(this WebViewPage view)
    {
        return Get(view, "id");
    }

    private static string Get(WebViewPage view, string key)
    {
        return view.ViewContext.Controller.ValueProvider.GetValue(key).RawValue.ToString();
    }
}

You really don't need to use the Generic version as the generic one extends the non-generic one so just put it in the non-generic base class and you're done :)

查看更多
登录 后发表回答