我有一个班级Character
,可存储3个CharacterAttribute
班级。我想要的是,如果在Character
个类之一内引发事件,CharacterAttribute
会在某一点上做某事。
class Character
{
public CharacterAttribute Physical;
public Character Create(...)
{
Physical = new CharacterAttribute();
Physical.SkillPointGained += this.OnSkillPointGained();
// ERROR: cannot convert void to System.EventHandler
}
public void OnSkillPointGained()
{
// do stuff here after the event has been fired
}
}
class CharacterAttribute
{
public event EventHandler SkillPointGained;
public void GainExperience(...)
{
SkillPointGained(this, new EventArgs()); // would raise the event here
}
}
我得到一个"无法隐式地将void转换为System.EventHandler"错误。我错过了什么?
答案 0 :(得分:3)
需要修改两行代码。
public void OnSkillPointGained()
应为:
void OnSkillPointGained(object sender, EventArgs e)
和
Physical.SkillPointGained += this.OnSkillPointGained();
应阅读:
Physical.SkillPointGained += this.OnSkillPointGained;
(...但是我更喜欢Marc的优雅答案。)
答案 1 :(得分:1)
EventHandler
的代理签名为void EventHandler(object sender, EventArgs args)
。你是:匹配错误的签名,b:你调用方法,而不是将方法作为委托。
但你可以作弊:
Physical.SkillPointGained += delegate { this.OnSkillPointGained(); };
这会创建一个匿名方法,充当立即处理程序,删除发件人/ args,并调用OnSkillPointGained
方法。