我尝试编写一个事件,当调用时会在屏幕上输出“right”,但不知为何无法正常工作。您能帮我找出问题所在吗?
我已经尝试使用+=
来触发事件,并且还尝试将对象更改为var引用,但依旧无法使事件生效。以下是代码:
// 文件:Program.cs
using PlayerMoveEvent1;
using PlayerMoveEvent2;
using PlayerMoveEvent3;
using PlayerMoveEvent4;
using PlayerMoveEvent5;
using MovementSpace;
class Program
{
static void Main(string[] args)
{
// 定义事件所需的对象:
var playerMoved = new PlayerMoves();
var moveRight = new MoveRight();
Movement movement = new Movement();
Console.ReadKey();
if (Console.ReadKey().Key == ConsoleKey.UpArrow)
{
Console.WriteLine("\n你向前移动了。");
}
else if (Console.ReadKey().Key == ConsoleKey.DownArrow)
{
Console.WriteLine("\n你向后移动了。");
}
else if (Console.ReadKey().Key == ConsoleKey.LeftArrow)
{
}
else if (Console.ReadKey().Key == ConsoleKey.RightArrow)
{
playerMoved.Move(movement);
playerMoved.PlayerMoved += moveRight.OnPlayerMoved;
}
else
{
System.Console.WriteLine("\n这不是有效的移动方向。");
System.Console.WriteLine("请再试一次。");
}
}
}
// 文件:MovementRight.cs
using System;
namespace PlayerMoveEvent2
{
public class MoveRight
{
public void OnPlayerMoved(object source, EventArgs args)
{
Console.WriteLine("\n右");
}
}
}
// 文件:PlayerMove.cs
using System;
using MovementSpace;
namespace PlayerMoveEvent1
{
public class PlayerMoves
{
public delegate void PlayerMovesEventHandler(object source, EventArgs args);
public event PlayerMovesEventHandler PlayerMoved;
public void Move(Movement movement)
{
Console.WriteLine("\n你朝这个方向移动了:");
OnPlayerMoved();
}
protected virtual void OnPlayerMoved()
{
if (PlayerMoved != null)
{
PlayerMoved(this, EventArgs.Empty);
}
}
}
}