试图通过使用委托实现观察者,我得到错误:不能隐式转换类型'void'到我的委托所属的类
本文关键字:类型 转换 void 我的 错误 实现 观察者 不能 | 更新日期: 2023-09-27 18:09:15
// subject
class SafeMode
{
private bool m_enable = false;
public bool Disable()
{
return m_enable;
}
public delegate void NotifyObserversHandler(bool _status);
public event NotifyObserversHandler DiableCommands;
public void Notify()
{
DiableCommands(m_enable);
}
}
public interface ICommand
{
void Execute(User i_User, string i_ButtonText, List<Photo> o_Photos);
void DiableFunctionality();
}
// my only observer
public class MostPopularPic : ICommand
{
public void DisableFunctionality()
{
m_enable = false;
}
}
// at other form class that's where i attach my observer to the delegate and the error occurs.
foreach( KeyValuePair<string,ICommand> runner in tmp)
{
ICommand curr = runner.Value;
m_safer.DiableCommands += curr.DiableFunctionality();
// faild to convert 'void' to 'SafeMode.NotifyObserversHandler'
}
看下面的语句:
m_safer.DiableCommands += curr.DiableFunctionality();
这是试图调用 curr.DiableFunctionality
,然后将方法调用的结果订阅到m_safer.DiableCommands
事件。
您现在不想调用该方法-您只想将方法组转换为委托,并订阅该委托。所以你想要:
m_safer.DiableCommands += curr.DiableFunctionality;
这仍然会有一个问题-你的DiableFunctionality
方法是无参数的,而你的NotifyObserversHandler
委托有一个bool
参数。如果您想忽略该参数,可以使用:
m_safer.DiableCommands += ignored => curr.DiableFunctionality();
现在使用一个lambda表达式,该表达式接受单个参数(ignored
)并忽略它,只调用curr.DiableFunctionality()
。