CS1106扩展方法必须在非泛型静态类中定义

时间:2017-01-24 10:36:40

标签: c# wpf

我一直在研究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);
    }
}

我需要做些什么来解决这个问题?

4 个答案:

答案 0 :(得分:11)

  

public void MoveTo(此Image target,double newY)

方法定义的第一个参数上的

this表示一个扩展方法,正如错误消息所述,它只对非泛型静态类有意义。你的课不是静态的。

这似乎不是作为扩展方法有意义的东西,因为它会对相关实例起作用,因此请删除this

答案 1 :(得分:1)

下次请先谷歌

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

扩展方法需要在静态类中定义。 从方法签名“MoveTo”中删除this关键字。

这样:

compile 'com.github.paolorotolo:appintro:4.1.0'

应该是这样的:

public void MoveTo(this Image target, double newY)

答案 2 :(得分:0)

MoveTo是一个扩展方法 - 它只是一个静态函数的语法糖,所以你可以调用

image.MoveTo(2.0)

而不是

SomeUtilityClass.MoveTo(image, 2.0)

但是扩展方法必须放在静态类中,因此不能将它放在Window类中。您可以在声明中省略“this”关键字,并将其用作静态方法,或者您需要将方法移动到静态类。

答案 3 :(得分:0)

将关键字static添加到类声明:

public static class ClassName{}