扩展方法需要“这个”?

时间:2012-11-15 12:03:24

标签: c# asp.net extension-methods

  

可能重复:
  Why is the ‘this’ keyword required to call an extension method from within the extended class

使用Visual Studio 2012

Sitefinity 5. *为命名空间System.Web.UI.MasterPage中的Telerik.Sitefinity.Web.UI定义了一些扩展方法。

如果我包含对该命名空间的引用,我可以使用一个特定的扩展方法来指示页面正常呈现,或者由内部搜索引擎:

using Telerik.Sitefinity.Web.UI;

namespace MyWebApp
{
    public partial class MyMasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            /// hide common page elements.
            /// GetIndexRenderMode() returns "Normal" if the page is being rendered
            /// normally, but not if the search engine is indexing the page.
            if (this.GetIndexRenderMode() != IndexRenderModes.Normal)
            {
                headerPlaceholder.Visible = false;
                footerPlaceholder.Visible = false;
                navigationPlaceholder.Visible = false;
            }
        }
    }
}

但是,如果我从this语句中删除if(...),编译器将不再找到扩展方法。

是什么给出的?除了解决类成员和接口成员或参数之间的歧义之外,我从未见过需要this的情况。

1 个答案:

答案 0 :(得分:2)

每个扩展方法都是某个类的扩展 您需要该类的实例才能使用该扩展名 在您的情况下,扩展名是MasterPage的一个实例,您可以在MasterPage的派生实例中使用它。因此,您需要this

相关问题