简体   繁体   English

隐式“ this”不能引用Xamarin中的扩展方法

[英]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. 我将我的名称空间导入了扩展所在的位置,然后尝试使用隐式this调用它(因此未指定它),但它不起作用。

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. 然后我添加了this. before the Constrain method call, it works, like so: Constrain方法调用之前,它的工作原理如下:

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?)? 这是Xamarin的C#实现中的缺陷吗?还是应该这样(如果这样,为什么?)?

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: C#规范的 7.6.5.2节-扩展方法调用中指定了调用扩展方法的语法,并显示为:

7.6.5.2 Extension Method Invocations 7.6.5.2扩展方法调用
In a method invocation (§7.5.5.1) of one of the forms 在以下形式之一的方法调用(第7.5.5.1节)中

 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. 如果expr或任何arg具有动态编译时类型,则扩展方法将不适用。

You can see that the legal forms involve expr. 您可以看到法律形式涉及expr. , something which isn't present when you call methods declared in the same type. ,当您调用以相同类型声明的方法时,这些不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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