使用委托来简化函数调用
我有一个布尔函数,用于许多其他函数的决策。每次,用户要么收到一个消息框,要么被允许继续,具体取决于该函数的返回值。所以我的伪代码可能如下所示:
private bool IsConsented()
{
//some business logic
}
private void NotReal()
{
if (IsConsented())
{
//call function A
}
else
{
MessageBox.Show("Need consent first.");
}
}
private void NotReal2()
{
if (IsConsented())
{
//call function B
}
else
{
MessageBox.Show("Need consent first.");
}
}
我正在寻找一种更简单的方法来执行此操作,而不是将 if-else 逻辑硬编码到我的每个函数中。我希望能够有一个像这样的函数:
private void CheckConsent(function FunctionPointer)
{
if (IsConsented())
{
//call the function
FunctionPointer();
}
else
{
MessageBox.Show("Need consent first.");
}
}
这样我就可以传递一个指向函数的指针。我确实怀疑这与委托有关,但我不知道语法,也不明白如何使用委托传递参数。
I have a boolean function which is used in the decision-making of many other functions. And every time, the user is either given a message box or allowed to proceed, depending on the return value of that function. So my pseudo-code might look like this:
private bool IsConsented()
{
//some business logic
}
private void NotReal()
{
if (IsConsented())
{
//call function A
}
else
{
MessageBox.Show("Need consent first.");
}
}
private void NotReal2()
{
if (IsConsented())
{
//call function B
}
else
{
MessageBox.Show("Need consent first.");
}
}
I am looking for a simpler way to do this, rather than hard-coding that if-else logic into every single function of mine. I'd like to be able to have a function like:
private void CheckConsent(function FunctionPointer)
{
if (IsConsented())
{
//call the function
FunctionPointer();
}
else
{
MessageBox.Show("Need consent first.");
}
}
So that I can just pass a pointer to a function. I have a real suspicion that this has to do with delegates, but I don't know the syntax, and I don't understand how to pass parameters around using delegates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要声明委托(或使用内置委托,例如 Action):
然后您可以执行以下操作:
You need to declare the delegate (or use a built-in one, such as Action):
You could then do:
里德·科普西的做法是干净的。它使用已经定义的 Action 委托和 lambda 表达式。但如果您对此不满意,这里是旧的做法。
您现在可以致电
Reed Copsey way of doing is clean one. It uses the Action delegate already defined along with lambda expression. But if you are not comfortable with that here is the old way of doing .
You can now call