2010-07-13 8 views

Répondre

10

Vous pouvez stocker la fonction dans un 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) 
{ 
    //... 
} 
+0

C'était exactement ce dont j'avais besoin! De plus, je viens d'apprendre quelque chose de nouveau ... Lambda Expressions * va enquêter * –

2

Bien sûr peut, j'ai écrit récemment un programme pour mon travail qui fait cela et plus encore. Mettre en œuvre un command pattern. Conceptuellement, c'est comme une télécommande programmable. Il permet également des transactions et d'autres petites fonctionnalités soignées.

2

Regardez les événements d'implémentation. C'est exactement ce qu'ils sont pour.

// 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) { /*...*/ } 
} 
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(); 
} 

espoir que est ce que vous cherchez!

Questions connexes