wpf CS1106 扩展方法必须在非泛型静态类中定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41825940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CS1106 Extension method must be defined in a non-generic static class
提问by Gal Didi
I've been working on a project in WPF C# and I'm trying to animate an image to move down. I have found the "MoveTo" function on the Internet and when I pasted it in the code the error occurred.
我一直在 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);
}
}
What I need to do to fix this?
我需要做什么来解决这个问题?
回答by Jon Hanna
public void MoveTo(this Image target, double newY)
public void MoveTo(this Image target, double newY)
thison the first argument of a method definition indicates an extension method which, as the error message says, only makes sense on a non-generic static class. Your class isn't static.
this在方法定义的第一个参数上表示一个扩展方法,正如错误消息所说,它只对非泛型静态类有意义。你的课程不是静态的。
This doesn't seem to be something that makes sense as an extension method, since it's acting on the instance in question, so remove the this.
这似乎不是作为扩展方法有意义的东西,因为它作用于有问题的实例,所以删除this.
回答by Pawe? S?owik
MoveTo is an extension method - it's just a syntactic sugar for a static function, so you can call
MoveTo 是一个扩展方法——它只是一个静态函数的语法糖,所以你可以调用
image.MoveTo(2.0)
instead of
代替
SomeUtilityClass.MoveTo(image, 2.0)
However extension methods must be placed in a static class, so you cannot place it in your Window class. You can just omit "this" keyword in the declaration and use it like a static method or you need to move the method to a static class.
但是,扩展方法必须放在静态类中,因此您不能将其放在 Window 类中。您可以在声明中省略“this”关键字并将其用作静态方法,或者您需要将该方法移动到静态类。
回答by shahar eldad
Please google first next time
下次请先google
https://msdn.microsoft.com/en-us/library/bb397656.aspx
https://msdn.microsoft.com/en-us/library/bb397656.aspx
Extension methods needs to be defined in a static class. Remove the this keyword from the method signature "MoveTo".
扩展方法需要在静态类中定义。从方法签名“MoveTo”中删除 this 关键字。
this:
这个:
public void MoveTo(this Image target, double newY)
should be like this:
应该是这样的:
public void MoveTo(Image target, double newY)
回答by Nag
Add keyword static to class declaration:
在类声明中添加关键字 static:
public static class ClassName{}

