你如何写一个C#扩展方法对于一般地类型类 [英] How do you write a C# Extension Method for a Generically Typed Class

查看:145
本文介绍了你如何写一个C#扩展方法对于一般地类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该有希望成为一个简单的。

This should hopefully be a simple one.

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

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 "";
        }
    }
}

解决方案

一般的解决方案是<一个href=\"http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772\">this回答。

要扩展System.Web.Mvc.ViewPage类的具体解决方案是<一个href=\"http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802\">my回答的下面,其从<一开始href=\"http://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772\">general解决方案。

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.

推荐答案

我不已经安装了当前机器上VS,但我认为语法是:

I don't have VS installed on my current machine, but I think the syntax would be:

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

这篇关于你如何写一个C#扩展方法对于一般地类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆