2010-10-25 6 views
9

Je souhaite être en mesure de transmettre une méthode en tant que paramètre.Passer une méthode en paramètre

par exemple ..

//really dodgy code 
public void PassMeAMethod(string text, Method method) 
{ 
    DoSomething(text); 
    // call the method 
    //method1(); 
    Foo(); 
} 

public void methodA() 
{ 
    //Do stuff 
} 


public void methodB() 
{ 
    //Do stuff 
} 

public void Test() 
{ 
    PassMeAMethod("calling methodA", methodA) 
    PassMeAMethod("calling methodB", methodB) 
} 

Comment puis-je faire cela?

+0

Vous devriez être capable de le faire avec des délégués. – jimplode

+0

Quelle version du framework .NET utilisez-vous? –

+0

3.5, quelqu'un peut-il me montrer en utilisant l'exemple ci-dessus? merci – raklos

Répondre

19

Vous devez utiliser un délégué, qui est une classe spéciale qui représente une méthode. Vous pouvez définir votre propre délégué ou utiliser l'un des délégués, mais la signature du délégué doit correspondre à la méthode que vous voulez passer.

Définition de votre propre:

public delegate int MyDelegate(Object a); 

Cet exemple correspond à une méthode qui retourne un entier et prend une référence d'objet en tant que paramètre.

Dans votre exemple, methodA et methodB ne prennent aucun paramètre et renvoient void, donc nous pouvons utiliser la classe déléguée d'action intégrée.

Voici votre exemple modifié:

public void PassMeAMethod(string text, Action method) 
{ 
    DoSomething(text); 
    // call the method 
    method();  
} 

public void methodA() 
{ 
//Do stuff 
} 


public void methodB() 
{ 
//Do stuff 
} 

public void Test() 
{ 
//Explicit 
PassMeAMethod("calling methodA", new Action(methodA)); 
//Implicit 
PassMeAMethod("calling methodB", methodB); 

} 

Comme vous pouvez le voir, vous pouvez utiliser le type de délégué explicitement ou implicitement, selon ce qui vous convient.

7

Utilisez Action<T>

Exemple:

public void CallThis(Action x) 
{ 
    x(); 
} 

CallThis(() => { /* code */ }); 
5

Ou Func <>

Func<int, string> func1 = (x) => string.Format("string = {0}", x); 
PassMeAMethod("text", func1); 

public void PassMeAMethod(string text, Func<int, string> func1) 
{ 
    Console.WriteLine(func1.Invoke(5)); 
} 
0

bâtiment sur ce BrunoLM a fait, comme cet exemple a été brève.

//really dodgy code 
public void PassMeAMethod(string text, Action method) 
{ 
    DoSomething(text); 
    method(); 
    Foo(); 
} 

// Elsewhere... 

public static void Main(string[] args) 
{ 
    PassMeAMethod("foo",() => 
     { 
      // Method definition here. 
     } 
    ); 

    // Or, if you have an existing method in your class, I believe this will work 
    PassMeAMethod("bar", this.SomeMethodWithNoParams); 
} 
+0

Pouvez-vous utiliser 'this' dans un vide statique? –

2

Delegates sont les fonctionnalités linguistiques que vous devrez utiliser pour accomplir ce que vous essayez de faire.

Voici un exemple en utilisant le code que vous avez ci-dessus (en utilisant le délégué Action comme raccourci):

//really dodgy code 
public void PassMeAMethod(string text, Action method) 
{ 
    DoSomething(text); 
    method(); // call the method using the delegate 
    Foo(); 
} 

public void methodA() 
{ 
    Console.WriteLine("Hello World!"); 
}  

public void methodB() 
{ 
    Console.WriteLine("42!"); 
} 

public void Test() 
{ 
    PassMeAMethod("calling methodA", methodA) 
    PassMeAMethod("calling methodB", methodB) 
} 
0

C# .net2.0 - Permettez-moi de montrer une réponse détaillée pour le sujet (pass-a-method-as-a-parameter). Dans mon scénario, je configure un ensemble de System.Timers.Timer -s, chacun avec une méthode différente _Tick.

delegate void MyAction(); 

// members 
Timer tmr1, tmr2, tmr3; 
int tmr1_interval = 4.2, 
    tmr2_interval = 3.5; 
    tmr3_interval = 1; 


// ctor 
public MyClass() 
{ 
    .. 
    ConfigTimer(tmr1, tmr1_interval, this.Tmr_Tick); 
    ConfigTimer(tmr2, tmr2_interval, (sndr,ev) => { SecondTimer_Tick(sndr,ev); }); 
    ConfigTimer(tmr3, tmr3_interval, new MyAction((sndr,ev) => { Tmr_Tick((sndr,ev); })); 
    .. 
} 

private void ConfigTimer(Timer _tmr, int _interval, MyAction mymethod) 
{ 
    _tmr = new Timer() { Interval = _interval * 1000 }; 
    // lambda to 'ElapsedEventHandler' Tick 
    _tmr.Elpased += (sndr, ev) => { mymethod(sndr, ev); }; 
    _tmr.Start(); 
} 

private void Tmr_Tick(object sender, ElapsedEventArgs e) 
{ 
    // cast the sender timer 
    ((Timer)sender).Stop(); 
    /* do your stuff here */ 
    ((Timer)sender).Start(); 
} 

// Another tick method 
private void SecondTimer_Tick(object sender, ElapsedEventArgs e) {..} 
Questions connexes