在侦听器函数中调用函数
本文关键字:函数 调用 侦听器 | 更新日期: 2023-09-27 18:14:58
我是c#世界的新手,我正在尝试使用下面的代码调用侦听器内部的另一个函数:
private void Form1_Load(object sender, EventArgs e)
{
listener = new GestureListener(100);
listener.onGesture += listener_onGesture;
controller = new Controller(listener);
}
static void listener_onGesture(Gesture gesture)
{
string gestures = "";
foreach (Gesture.Direction direction in gesture.directions) {
gestures = direction.ToString();
}
int howManyFingers = gesture.fingers;
if (gestures == "Left" && howManyFingers == 2) {
test();
} else {
Console.WriteLine("gestured " + gestures + " with " + gesture.fingers + " fingers.");
}
}
private void test()
{
pdf.gotoNextPage();
}
然而,它似乎不工作,当我这样做。它在test();这行给我的错误是:
非静态字段、方法或属性'LeapDemoTest.Form1.test()'需要对象引用
我该怎么做?
您看到这一点是因为listener_onGesture
是一个静态方法——也就是说,该方法不与类的给定实例相关联。然而,test
是一个实例方法——因此它的作用域为特定的实例。
我看到三个选项,取决于"pdf"的范围,但我推荐选项1:
- 使
listener_onGesture
成为实例方法(去掉static
关键字) - 让
test
成为一个静态方法——这只会在pdf
也是一个静态成员的情况下起作用。 - 有点粗糙——通过检查
sender
的属性找到调用该事件的Form
实例,并在该实例上调用test
方法。
listener_onGesture
可能不应该是静态的。您希望访问该方法中的实例字段,并且似乎是从应用程序的实例中调用它(当前引用它的Form1_Load
不是静态方法)。通过从该方法中删除static
修饰符,您将能够调用非静态方法。