C# 在侦听器函数中调用函数

C# 在侦听器函数中调用函数,c#,function,listener,C#,Function,Listener,我是C#世界的新手,我正在尝试使用以下代码调用侦听器中的另一个函数: private void Form1_Load(object sender, EventArgs e) { listener = new GestureListener(100); listener.onGesture += listener_onGesture; controller = new Controller(listener); }

我是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();
    }
然而,当我这样做时,它似乎不起作用。它在测试()行上给我的错误是:

非静态字段、方法或属性“LeapDemost.Form1.test()”需要对象引用


我怎样才能做到这一点呢?

监听器\u onGesture
可能不应该是静态的。您希望访问此方法中的实例字段,并且似乎是从应用程序的实例中调用它(
Form1\u Load
,您当前引用它的位置,不是静态方法)。通过从该方法中删除
static
修饰符,您将能够调用非静态方法。

您看到这一点,因为
listener\u onGesture
是一个静态方法,也就是说,该方法与类的给定实例没有关联。但是,
test
是一个实例方法——因此它的作用域是特定实例

根据“pdf”的范围,我看到三个选项,但我建议选项1:

  • 使
    listener\u onGesture
    成为一个实例方法(删除
    static
    关键字)
  • 使
    test
    成为一个静态方法——这仅在
    pdf
    也是静态成员时才有效
  • 有点黑——通过检查
    发送方
    的属性,找到调用事件的
    表单
    实例,并在该实例上调用
    测试
    方法

谢谢您的帮助,Servy!