希望这应该是一个简单的问题。

我想向 System.Web.Mvc.ViewPage< T > 类添加扩展方法。

这个扩展方法应该是什么样的?

我的第一个直觉想法是这样的:

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

解决方案

一般的解决方案是 这个答案.

扩展System.Web.Mvc.ViewPage类的具体解决方案是 我的答案 下面,从 通用解.

不同之处在于,在特定情况下,您需要泛型类型方法声明和语句来强制泛型类型作为引用类型。

有帮助吗?

解决方案

我当前的机器上没有安装 VS,但我认为语法是:

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

其他提示

谢谢莱德。这样做会产生错误:

“ Tmodel”类型必须是一种参考类型,以便将其用作通用类型或方法中的参数“ Tmodel”

这给我指出了 这一页, ,产生了这个解决方案:

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

它只需要函数上的泛型类型说明符:

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

编辑:就差几秒就错过了!

namespace System.Web.Mvc
{
    public static class ViewPageExtensions
    {
        public static string GetDefaultPageTitle<T>(this ViewPage<T> view)
            where T : class
        {
            return "";
        }
    }
}

您可能还需要/希望将“new()”限定符添加到泛型类型(即“其中 T :class, new()”强制 T 既是引用类型(类)又具有无参数构造函数。

格伦·布洛克 有一个很好的例子来实现 ForEach 扩展方法为 IEnumerable<T>.

从他的 博客文章:

public static class IEnumerableUtils
{
    public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
    {
        foreach(T item in collection)
            action(item);
    }
}

如果您希望扩展名仅适用于指定类型,则只需指定您要处理的实际类型

就像是...

public static string GetDefaultPageTitle(this ViewPage<YourSpecificType> v)
{
  ...
}

请注意,当您声明具有匹配类型的(在本例中)ViewPage 时,智能感知将仅显示扩展方法。

另外,最好不要使用 System.Web.Mvc 命名空间,我知道不必在 usings 部分中包含命名空间很方便,但如果您为扩展函数创建自己的扩展命名空间,则它的可维护性要高得多。

以下是 Razor 视图的示例:

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();
    }
}

您确实不需要使用通用版本,因为通用版本扩展了非通用版本,因此只需将其放入非通用基类中即可完成:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top