在 C# 的 lambda 事件处理程序中引用非静态字段
Referencing non-static field in lambda Event Handler in C#
我一直在使用 Unity 开发一个基本游戏,并且正在尝试编写代码来检测球何时 'stopped' 移动(即移动实际上为零)。我希望通过在位置更改事件处理程序内的多个帧上对球位置之间的差异进行采样,通过 eventargs 传递两个运动之间的差异来实现这一点。
然而,每当我尝试访问位置数组时,我都会收到此错误:A field initializer cannot reference the non-static field, method, or property 'Ball.locations'
我对具体发生的事情感到有些困惑,因为我对事件处理程序相当陌生,并且承认复制了底部的 lambda(因为它看起来更整洁)而没有真正理解它到底在做什么。
相关代码如下:
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!");
}
};
}
感谢您花时间阅读我的 post,非常感谢任何帮助理解这里发生的事情!
See this error description. 您不能在 EventHandler 中使用 locations.length。您在 'same' 时间同时定义此事件处理程序和 locations
数组。无论如何都不需要这个 if 语句。 5的长度不变。
我一直在使用 Unity 开发一个基本游戏,并且正在尝试编写代码来检测球何时 'stopped' 移动(即移动实际上为零)。我希望通过在位置更改事件处理程序内的多个帧上对球位置之间的差异进行采样,通过 eventargs 传递两个运动之间的差异来实现这一点。
然而,每当我尝试访问位置数组时,我都会收到此错误:A field initializer cannot reference the non-static field, method, or property 'Ball.locations'
我对具体发生的事情感到有些困惑,因为我对事件处理程序相当陌生,并且承认复制了底部的 lambda(因为它看起来更整洁)而没有真正理解它到底在做什么。
相关代码如下:
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!");
}
};
}
感谢您花时间阅读我的 post,非常感谢任何帮助理解这里发生的事情!
See this error description. 您不能在 EventHandler 中使用 locations.length。您在 'same' 时间同时定义此事件处理程序和 locations
数组。无论如何都不需要这个 if 语句。 5的长度不变。