【C#】Timer.Elapsed触发的方法里怎么传进去参数?

如图,我希望timer.Elapsed能触发KeyAction,那样我就可以用KeyAction里的方法获取键盘输入内容了。但因为keyPress是我自己声明的,所以参数跟Timer.Elapsed的不一样。我想知道怎么让报错的block1成功传进KeyAction

图片说明

using System;
using System.Timers;

namespace _8._19
{
    class Program
    {
        static void Main(string[] args)
        {
            Timer timer = new Timer();
            timer.Interval = 500;

            KeyBord keyBord = new KeyBord();
            Block block1 = new Block();
            keyBord.KeyPress += block1.BlockMove;

            timer.Elapsed += keyBord.TimerAction;

            Console.Read();
        }
    }
    public class Block
    {
        public void BlockMove(Block block, KeyEventArgs e)
        {
            Console.WriteLine("block move");//预留方法的位置
            Console.WriteLine(e.KeyInput);
        }
    }
    class KeyBord
    {
        public event KeyEventHandler KeyPress;
        public void KeyAction(Block block, KeyEventArgs e)
        {
            if (Console.KeyAvailable)
            {
                ConsoleKey key = Console.ReadKey().Key;
                if (key == ConsoleKey.D)
                {
                    e.KeyInput = ConsoleKey.D;
                    Console.WriteLine(" e.KeyInput = ConsoleKey.D;");//预留方法的位置
                }
                this.KeyPress.Invoke(block, e);
            }
        }
        public void TimerAction(object sender, ElapsedEventArgs e)
        {
            this.KeyAction(block1, new KeyEventArgs());
        }
    }
    public delegate void KeyEventHandler(Block block, KeyEventArgs e);
    public class KeyEventArgs
    {
        public ConsoleKey KeyInput { get; set; }
    }
}

1个回答

好吧,我自己用了一种笨解决办法,给keyboard声明了个block的属性,然后把block1赋给了keyboard.block,再this调用。
好蠢啊这么干。。。等一个好方法

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问