我正在寻找一些帮助理解事件.我一直在阅读关于它们的文章并观看教程视频.
我几乎理解他们,但我一直在遇到障碍.
我自己做了一个简单的WinForms测试应用程序来尝试和学习这个过程.在应用程序中,屏幕周围有2个行走的精灵.单击表单时,它会创建一个下降thwomp的精灵(并且它会创建一个事件),步行者精灵应该通过选择一个远离精灵的新步行路径来对事件做出反应.我想我已经写好了一切,但是当我编译它时我得到了错误:
错误1可访问性不一致:参数类型'eventStomper.RunEventArgs'比委托'eventStomper.RunInFear'更难访问
错误2不可访问性:参数类型'eventStomper.RunEventArgs'比方法'eventStomper.Walker.RunAway(object,eventStomper)更难访问. RunEventArgs)"
我很茫然,因为一切都是公开的.有关错误的任何建议吗?并且,有关事件处理的任何建议吗?
这里的源代码简化为相关位:
namespace eventStomper
{
public delegate void RunInFear(object sender, RunEventArgs re); //The delegate for responding to events.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
spawnWalkers(); //Create a couple of walkers to roam around the form
}
List<Thwomp> thowmpList = new List<Thwomp>(); //List of thwomps. This is iterated through for animation.
List<Walker> walkerList = new List<Walker>();// Same thing with the walkers.
public void pictureBox1_Click(object sender, EventArgs e) //When you click on the background, it spawns a thwomp
{
Point _spawnPoint = this.PointToClient(Cursor.Position);
Thwomp _thwomp = new Thwomp(_spawnPoint, sprite ); //Generate a new Thwomp
thowmpList.Add(_thwomp); //Add it to the list of Thwomps
_thwomp.TimeToRun += walkerList[0].RunAway; //Register with the two walkers roaming around.
_thwomp.TimeToRun += walkerList[1].RunAway;
//Do other things to setup the thwomp sprite
}
}
public class Thwomp
{
public int spriteX = 0;//Current sprite location
public int spriteY = 0;
public int targetX = 0;//Where the thwomp will land.
public int targetY = 0;
public event RunInFear TimeToRun;
public void Animate()
{
//Do Animation steps.
}
public Thwomp(Point spawnPoint, PictureBox spriteIncoming)
{
RunEventArgs re = new RunEventArgs();
re._pointOfFear = spawnPoint;
//Setup thwomp sprite
TimeToRun(this, re); //Trigger the event.
}
}
public class Walker
{
public int spriteX = 0; //Current sprite location
public int spriteY = 0;
public Walker(Point spawnPoint, PictureBox spriteIncoming)
{
//Create the walker
}
public void RunAway(Point dangerPoint)
{
if (Math.Abs(sprite.Top - dangerPoint.Y) < 20 && Math.Abs(sprite.Left - dangerPoint.X) < 20) //If near a newly created thwomp, run away.
{
//Pick a path headed away from the danger.
}
}
public void Animate()
{
//Move the walker away.
}
}
class RunEventArgs : EventArgs
{
public Point _pointOfFear;
}
}
Run Code Online (Sandbox Code Playgroud)
我很茫然,因为一切都是公开的.
不完全的.正如错误消息所示:
参数类型'eventStomper.RunEventArgs'比委托'eventStomper.RunInFear'更难访问
根据那条消息,RunEventArgs不太容易接近RunInFear.因此,让我们看看这两种类型的可访问性级别:
public delegate void RunInFear(object sender, RunEventArgs re);
Run Code Online (Sandbox Code Playgroud)
所以,这是公开的.到现在为止还挺好.
class RunEventArgs : EventArgs
{
public Point _pointOfFear;
}
Run Code Online (Sandbox Code Playgroud)
啊哈!这个没有分配的可访问性,这意味着 - 根据文档 - 它将默认为internal:
顶级类型(不嵌套在其他类型中)只能具有内部或公共可访问性.这些类型的默认可访问性是内部的.
因此,应该编译RunEventArgs该类public和您的代码.
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |