Tam*_*tin 5 c# events event-handling
我一直在研究其他许多答案和例子,我对如何设置这个问题越来越困惑.我需要根据表单类中的performMove方法的结果在Robot类中引发一个事件.我知道我不能从另一个班级提出这个事件,所以我显然不起作用.但我真的没有理解如何正确设置它.我已经阅读了有关codeProject,dreamInCode和本网站以及其他许多内容的代表和活动文章.这是一个初学者c#类,我对此很新,因为我相信每个人都可以告诉:)
namespace Assignment12
{
public delegate void ErrorHandler();
public partial class frmRobot : Form
{
Robot moveRobot = new Robot();
public frmRobot()
{
InitializeComponent();
reset_Position();
current_Position_Display();
moveRobot.outOfRange += new ErrorHandler(moveRobot.coor_Within_Range);
}
...
private void performMove()
{
Point loc = lblArrow.Location;
int x = moveRobot.Move_Robot_XAxis(loc.X);
int y = moveRobot.Move_Robot_YAxis(loc.Y);
if (x < -100 && x > 100)
{
moveRobot.outOfRange();
x = loc.X;
}
if (y < -100 && y > 100)
{
moveRobot.outOfRange();
y = loc.Y;
}
this.lblArrow.Location = new Point(x, y);
current_Position_Display();
}
class Robot
{
public event ErrorHandler outOfRange;
...
public void coor_Within_Range()
{
System.Console.WriteLine("TestOK");
}
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 13
这个问题很混乱.
你应该向自己提出的问题是:谁负责宣布和执行政策?你有两个实体:"形式"和"机器人".您对机器人的法律地位有一些政策.哪个班级负责制定该政策?机器人是否知道它何时超出范围,并告知该事实的形式?或者,当机器人超出范围时,表格是否知道,并且它会通知机器人这个事实?
希望被告知的事情是事件监听者.希望告知其他人违反政策的事情是事件来源.完全不清楚你想要成为听众的哪一个,以及你想成为哪个来源.但是你违反的规则很明确: 事件监听器不是事件发生时允许说的事情.该人士听完音乐会没有得到站起来,大喊指令钢琴家什么键按下!那是钢琴家的决定,听众只是决定是否听,以及如何反应.
如果表单决定机器人何时超出范围,那么机器人需要成为听众.如果机器人决定表单何时超出范围,那么表单需要成为收听者.现在你已经把这个形式作为听众了,但是它试图告诉机器人何时超出范围.
您coor_Within_Range提出该事件的需求:
public void coor_Within_Range()
{
System.Console.WriteLine("TestOK");
if (this.outOfRange != null) {
this.outOfRange();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的Form班级中你需要处理该事件:
public frmRobot()
{
// snipped
moveRobot.outOfRange += new ErrorHandler(this.oncoor_Within_Range);
}
public void oncoor_Within_Range() {
Console.WriteLine("robot within range");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
516 次 |
| 最近记录: |