隐式 'this' 无法在 Xamarin 中引用扩展方法

Implicit 'this' cannot reference extension methods in Xamarin

我创建了一个自定义扩展方法,以便在代码中更轻松地向视图添加约束。现在,当我想使用它时,我无法让它工作。我在扩展所在的位置导入了我的名称空间,并尝试使用隐式 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*/);
    }
}

没用。然后我在 Constrain 方法调用之前添加了 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()
    {
        this.Constrain(/*parameters*/);
    }
}

这是 Xamarin 的 C# 实现中的缺陷还是应该是这样的(如果是,为什么?)?

这根本不是允许语法的一部分。

调用扩展方法的语法在 C# Specification 节 7.6.5.2 - 扩展方法调用中指定,显示为:

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.

您可以看到合法形式涉及 expr.,当您调用以相同类型声明的方法时,这些内容并不存在。