簡體   English   中英

CS1106擴展方法必須在非泛型靜態類中定義

[英]CS1106 Extension method must be defined in a non-generic static class

我一直在研究WPF C#中的一個項目,我試圖讓圖像動畫下移。 我在Internet上找到了“MoveTo”功能,當我將其粘貼到代碼中時發生了錯誤。

Public partial class Window1: Window
{
    public static int w = 1;

    public Window1()
    {
        InitializeComponent();

    }

    public void MoveTo(this Image target, double newY)
    {
        var top = Canvas.GetTop(target);
        TranslateTransform trans = new TranslateTransform();
        target.RenderTransform = trans;
        DoubleAnimation anim1 = new DoubleAnimation(top, newY - top, TimeSpan.FromSeconds(10));
        trans.BeginAnimation(TranslateTransform.XProperty, anim1);
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        MoveTo(image, 130);
    }
}

我需要做些什么來解決這個問題?

public void MoveTo(此圖像目標,雙newY)

this在方法定義的第一個參數上表示一個擴展方法,正如錯誤消息所說,它只對非泛型靜態類有意義。 你的班級不是靜態的。

這似乎不是作為擴展方法有意義的東西,因為它正在對有問題的實例起作用,所以刪除this

請下次谷歌第一次

https://msdn.microsoft.com/en-us/library/bb397656.aspx

擴展方法需要在靜態類中定義。 從方法簽名“MoveTo”中刪除this關鍵字。

這個:

public void MoveTo(this Image target, double newY)

應該是這樣的:

public void MoveTo(Image target, double newY)

MoveTo是一個擴展方法 - 它只是一個靜態函數的語法糖,所以你可以調用

image.MoveTo(2.0)

代替

SomeUtilityClass.MoveTo(image, 2.0)

但是,擴展方法必須放在靜態類中,因此不能將它放在Window類中。 您可以在聲明中省略“this”關鍵字並將其用作靜態方法,或者您需要將方法移動到靜態類。

將關鍵字static添加到類聲明:

public static class ClassName{}

暫無
暫無

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

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