簡體   English   中英

隱式“ 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*/);
    }
}

哪個沒有用。 然后我添加了this. 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*/);
    }
}

這是Xamarin的C#實現中的缺陷嗎?還是應該這樣(如果這樣,為什么?)?

這根本不是允許的語法的一部分。

C#規范的 7.6.5.2節-擴展方法調用中指定了調用擴展方法的語法,並顯示為:

7.6.5.2擴展方法調用
在以下形式之一的方法調用(第7.5.5.1節)中

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

如果調用的正常處理未找到適用的方法,則嘗試將構造作為擴展方法調用進行處理。 如果expr或任何arg具有動態編譯時類型,則擴展方法將不適用。

您可以看到法律形式涉及expr. ,當您調用以相同類型聲明的方法時,這些不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM