开发者

Problem calling extension method on a ViewPage

开发者 https://www.devze.com 2023-02-24 17:18 出处:网络
I created the following extension method for a ViewPage: using System.Web.Mvc; namespace G3Site { public static class ViewPage_Extensions {

I created the following extension method for a ViewPage:

using System.Web.Mvc;

namespace G3Site {
    public static class ViewPage_Extensions {
        public static void Test(this ViewPage vp) {
            vp.Writer.Write("this is a test");
        }
    }
}

I then put an import statement on my aspx page

<%@ Import Namespace="G3Site" %开发者_C百科>

I can call the Test() method through this just fine:

<% this.Test(); %>

But when I try to call it without reference to this:

<% Test(); %>

I get a compiler error:

CS0103: The name 'Test' does not exist in the current context

Does anyone have any idea why this is happening and is there a way around it?


It is a requirement of the C# compiler that extension methods are called 'off' of an expression (such as a variable or reference to an object) per the C# language specification (section 7.6.5.2).


This isn't just a limitation of the ASP.Net MVC view, this is a general rule for extension methods in C#:

public class SomeClass
{
    public void Method()
    {
        ExtensionMethod();
    }
}

public static class Extensions
{
    public static void ExtensionMethod(this SomeClass sc) { }
}

This will not compile, as the C# compiler requires extension method to be called using an instance. Why this decision is so, is probably because of some corner case only Eric Lippert can dream up :)

0

精彩评论

暂无评论...
验证码 换一张
取 消