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



>我一直在用 WPF C# 做一个项目,我正在尝试对图像进行动画处理以向下移动。我在互联网上找到了"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);
    }
}

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

公共无效移动到(此图像目标,双新Y)

方法定义的第一个参数上的this表示扩展方法,如错误消息所述,该方法仅在非泛型静态类上有意义。您的类不是静态的。

这似乎作为扩展方法没有意义,因为它作用于有问题的实例,因此请删除this

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

image.MoveTo(2.0)

而不是

SomeUtilityClass.MoveTo(image, 2.0)

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

下次请先谷歌一下

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

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

这:

public void MoveTo(this Image target, double newY)

应该是这样的:

public void MoveTo(Image target, double newY)
<</div> div class="one_answers">

在类声明中添加关键字 staty:

public static class ClassName{}

最新更新