简体   繁体   English

在C#中的lambda事件处理程序中引用非静态字段

[英]Referencing non-static field in lambda Event Handler in C#

I've been developing a basic game in Unity and am attempting to write code to detect whenever a ball has 'stopped' moving (ie movement is effectively zero). 我已经在Unity中开发了一款基本游戏,并且试图编写代码来检测球何时“停止”运动(即运动实际上为零)。 I was hoping to achieve this by sampling the difference between the balls locations over a number of frames inside the position changed event handler, passing through the difference between two movements through the eventargs. 我希望通过在事件改变后的事件处理程序内的多个帧中采样球位置之间的差异,并通过eventargs两次移动之间的差异,来实现这一目标。

However whenever I try to access the locations array I get this error: A field initializer cannot reference the non-static field, method, or property 'Ball.locations' 但是,每当我尝试访问locations数组时,都会出现此错误: A field initializer cannot reference the non-static field, method, or property 'Ball.locations'

I'm slightly confused as to what specifically is occurring, as I'm rather new to event handlers and admittedly copied the bottom lambda (because it looked tidier) without really understanding what exactly it is doing. 我对具体发生的事情有些困惑,因为我对事件处理程序还很陌生,并且在没有真正理解其实际操作的情况下,承认复制了底部的lambda(因为它看起来更简洁)。

Here is the relevant code: 以下是相关代码:

public class Ball : IBall {
    private float[] locations = new float[5];

    public Ball() {

    }

    public Vector3 Position {
        get { return position; }
        set {
            if (position != value) {
                BallMovedEventArgs eventArgs = new BallMovedEventArgs (position, value);
                position = value;
                OnMove (this, eventArgs);
            }
        }
    }

    public event EventHandler<BallMovedEventArgs> OnMove = (sender, e) => {
        // error is thrown here
        if(locations.Length > 5) {
            Debug.Log("Too many location deltas!");
        }
    };
}

Thanks for taking the time to read my post, any help in understanding what is happening here is much appreciated! 感谢您抽出宝贵的时间阅读我的帖子,非常感谢您对理解这里发生的事情有任何帮助!

See this error description. 请参阅此错误描述。 You can't use locations.length in the EventHandler. 您不能在EventHandler中使用locations.length。 You are defining both this event handler and the locations array at the 'same' time. 您将在“相同”时间定义此事件处理程序和locations数组。 It seems like this if statement isn't needed anyhow. 好像这样的if语句无论如何都不需要。 The length of 5 is constant. 5的长度是恒定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM