我有一个处理消息(或命令)的方法。然而 mModuleSimulation 是另一个类的实例,这个类做一些异步的事情,完成后它需要将结果发送到另一台计算机。 mModuleSimulation 类不知道如何发送,这就是我用它发送我的 SendData 方法的原因,因此它可以简单地调用该方法。
public void HandleMessage(ITCCommand command, string address)
{
mModuleSimulation.ExecuteReceived(SendData, command.Name, address);
}
internal void SendData(string command, string tcAddress)
{
//DoSend command to address stuff
}
现在不得不传递一个方法已经够糟糕了(至少我不认为这是好的做法,尽管可能是错误的)。但是此方法 SendData 需要一个地址才能发送到。正如您在示例中看到的那样,我目前正在发送地址。
当一切都完成后,我这样调用它:
SendData.Invoke(message, address);
有没有一种方法(无需更改 SendData 方法)只需执行以下操作:SendData.Invoke(message) 这样我就不必在每个方法中都传递地址。
是否可以这样做(我知道这完全行不通,但这只是为了让您了解我的要求):
public void HandleMessage(ITCCommand command, string address)
{
Action<string, string> sendDataAction = this.SendData.**SetArgument(arg1 = address)**;
mModuleSimulation.ExecuteReceived(sendDataAction , command.Name);
}
请您参考如下方法:
传递方法(或函数)非常好——它又流行起来了:)
对于您的情况,闭包是完美的解决方案。你的SendData方法需要两个参数,但您可以捕获参数而不必手动传递它 - lambda 函数使这变得微不足道:
public void HandleMessage(ITCCommand command, string address)
{
mModuleSimulation.ExecuteReceived(cmd => SendData(cmd, address), command.Name);
}
internal void SendData(string command, string tcAddress)
{
//DoSend command to address stuff
}
这样,您传递的代表已经有了 address捕获,它自己的签名很简单 Action<string> .您隐藏了 SendData 的实现细节来自 ExecuteReceived 的方法老实说根本不关心的方法 - 它只是想调用 Action<string> .
如果这让您感到不安,那就想想委托(delegate)到底是什么——在简单的 OOP 中,它是一个使用单一方法实现接口(interface)的类。你几乎找不到比这更的 OOP :D
这完全类似于手动执行这样的操作:
interface ISendData
{
void SendData(string command);
}
class SendData : ISendData
{
private readonly string address;
public SendData(string address)
{
this.address = address;
}
public void SendData(string command)
{
InternalSendData(command, address);
}
}
public void HandleMessage(ITCCommand command, string address)
{
var mySendData = new SendData(address);
mModuleSimulation.ExecuteReceived(mySendData, command.Name);
}
你只是节省了一些不必要的代码:)
