我有一个循环,需要在循环完成后“标记”函数以便稍后运行。这可能吗?
谢谢,泰勒
答案 0 :(得分:10)
您可以将该功能存储在delegate:
中private void Test(object bar)
{
// Using lambda expression that captures parameters
Action forLater = () => foo(bar);
// Using method group directly
Action<object> forLaterToo = foo;
// later
forLater();
forLaterToo(bar);
}
private void foo(object bar)
{
//...
}
答案 1 :(得分:4)
Dictionary<Action, bool> functionsToRun = new Dictionary<Action, bool>();
functionsToRun.Add(() => { Console.WriteLine("This will not run"); }, false);
functionsToRun.Add(() => { Console.WriteLine("Run forest run!!!!!!"); }, true);
foreach (KeyValuePair<Action, bool> function in functionsToRun)
{
if (function.Value)
function.Key.Invoke();
}
希望这就是你要找的东西!
答案 2 :(得分:2)
当然可以,我最近为我的工作写了一个程序来做那个以及更多。实现command pattern.概念上它就像一个可编程遥控器。它还允许交易和其他整洁的小功能。
答案 3 :(得分:2)
了解实施事件。这正是它们的用途。
// define a delegate signature for your functions to implement:
public delegate void PostProcessingHandler(object sender, object anythingElse /*, etc.*/);
public class YourClass {
// define an event that will fire all attached functions:
public event PostProcessingHandler PostProcess;
public void YourMethod() {
while(someConditionIsTrue) {
// do whatever you need, figure out which function to mark:
switch(someValue) {
case "abc": PostProcess += new PostProcessingHandler(HandlerForABC); break;
case "xyz": PostProcess += new PostProcessingHandler(HandlerForXYZ); break;
case "123": PostProcess += new PostProcessingHandler(HandlerFor123); break;
default: break;
}
}
// invoke the event:
if(PostProcess != null) { PostProcess(); }
}
public void HandlerForABC(object sender, object anythingElse) { /*...*/ }
public void HandlerForXYZ(object sender, object anythingElse) { /*...*/ }
public void HandlerFor123(object sender, object anythingElse) { /*...*/ }
}