【问题标题】:Calling a function within a listener function在侦听器函数中调用函数
【发布时间】:2013-05-18 01:16:28
【问题描述】:

我是 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()”需要对象引用

我该怎么做?

【问题讨论】:

    标签: c# function listener


    【解决方案1】:

    您看到这个是因为listener_onGesture 是一个静态方法——意思是,该方法与您的类的给定实例无关。但是,test 是一个实例方法——所以它的作用域是特定的实例。

    我看到三个选项,取决于“pdf”的范围,但我推荐选项 1:

    • listener_onGesture 设为实例方法(删除static 关键字)
    • test 设为静态方法 -- 仅当 pdf 也是静态成员时才有效。
    • 有些骇人听闻 - 通过检查 sender 的属性找到调用事件的 Form 实例并在该实例上调用 test 方法。

    【讨论】:

      【解决方案2】:

      listener_onGesture 可能不应该是静态的。您想要访问此方法中的实例字段,并且您似乎是从应用程序的实例中调用它(您当前引用它的Form1_Load 不是静态方法)。通过从该方法中删除 static 修饰符,您将能够调用非静态方法。

      【讨论】:

      • 感谢您的帮助,Servy!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多