2010-11-22 2 views
25

J'utilise un délégué anonyme dans mon code appelant cet exemple fonction:Utilisation des types de retour de vide avec de nouveaux Func <T, TResult>

public static int TestFunction(int a, int b) { 
    return a + b; 
} 

Le délégué ressemble à ceci:

var del = new Func<int, int, int>(TestFunction); 

Ma question est: comment spécifiez-vous un type de retour void pour TResult? Ce qui suit ne fonctionne pas:

public static void OtherFunction(int a, string b) { ... } 
var del = new Func<int, string, void>(OtherFunction); 

Répondre

42

S'il n'y a pas de type de retour, vous voulez Action<int,string>:

var del = new Action<int, string>(OtherFunction); 

ou tout simplement:

Action<int, string> del = OtherFunction; 
6

Vous devez utiliser l'action < T> si vous voulez retourner void.

3

Vous avez besoin d'action < T> si vous ne voulez pas retourner quelque chose

0

Utiliser action au lieu de Func si vous ne avez pas besoin de valeur de retour

public void InvokeService<T>(Binding binding, string endpointAddress, Action<T> invokeHandler) where T : class 
    { 
     T channel = FactoryManager.CreateChannel<T>(binding, endpointAddress); 
     ICommunicationObject communicationObject = (ICommunicationObject)channel; 

     try 
     { 
      invokeHandler(channel); 
     } 
     finally 
     { 
      try 
      { 
       if (communicationObject.State != CommunicationState.Faulted) 
       { 
        communicationObject.Close(); 
       } 
      } 
      catch 
      { 
       communicationObject.Abort(); 
      } 
     } 
    }