简体   繁体   中英

Implicit 'this' cannot reference extension methods in Xamarin

I have created a custom extension method to make adding constraints to views easier to do in code. Now when I wanted to use it, I couldn't get it to work. I imported my namespace where the extesion resides, and I tried calling it using the implicit this (so without specifying it), and it didn't work.

So I had something like this:

public static class ExtensionMethods {

    public static void Constrain(this UIView view, /*parameters with some defaults*/)
    {
        view.AddConstraint( /*the same parameters*/ );
    }
}

public class MyCustomView: UIView
{
    public MyCustomView()
    {
        Constrain(/*parameters*/);
    }
}

Which didn't work. Then I added this. before the Constrain method call, it works, like so:

public static class ExtensionMethods {

    public static void Constrain(this UIView view, /*parameters with some defaults*/)
    {
        view.AddConstraint( /*the same parameters*/ );
    }
}

public class MyCustomView: UIView
{
    public MyCustomView()
    {
        this.Constrain(/*parameters*/);
    }
}

Is this a flaw in Xamarin's implementation of C# or is this supposed to be this way (if so, why?)?

This is simply not part of the allowed syntax.

The syntax for invoking extension methods is specified in the C# Specification , section 7.6.5.2 - Extension Method Invocations, and is shown as:

7.6.5.2 Extension Method Invocations
In a method invocation (§7.5.5.1) of one of the forms

 expr . identifier ( ) expr . identifier ( args ) expr . identifier < typeargs > ( ) expr . identifier < typeargs > ( args ) 

if the normal processing of the invocation finds no applicable methods, an attempt is made to process the construct as an extension method invocation. If expr or any of the args has compile-time type dynamic, extension methods will not apply.

You can see that the legal forms involve expr. , something which isn't present when you call methods declared in the same type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM