通过条件作为参数 [英] Passing a condition as a parameter

查看:74
本文介绍了通过条件作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像执行操作一样将条件作为参数传递?

Is it possible to pass a condition as parameter as you do with actions?

这是一个例子.

public void Test(Action action, Condition condition);

...

Test( () => Environment.Exit(0), () => variable == variable2 );

推荐答案

尝试将第二个参数传递为类型Func<Boolean>.该代码应该可以在问题的第二部分中正常工作

Try passing the second argument as type Func<Boolean>. The code should work as you have it in the second part of your question:

public void Text(Action action, Func<Boolean> condition) {
    if (condition()) action();
}

请注意,在使用示例中您将要做的是创建一个结束,其中包含捕获变量variable和variable2.在以这种方式使用闭包之前,您应该了解闭包的含义.

Note that what you would be doing in your usage example is creating a Closure containing the captured variables variable and variable2. You should understand the implications of closures before using them in this way.

这篇关于通过条件作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆