Csharping Rotating Header Image

Action vs Func

Action encapsula un método que tiene un parámetro como entrada y no devuelve ningún valor.
Func encapsula un método que tiene un parámetro de entrada y devuelve un objeto del tipo especificado en TResult.

Ambos pueden ser sustituidos por un delegado pero tienen la ventaja que al usarlos no tenemos que definir delegados como veremos en el siguiente par de ejemplos. En el primero usaremos action para mostrar un mensaje por pantalla y en el segundo usaremos func para contar el numero de letras de una cadena.

using System;
using System.Windows.Forms;

public class ExampleAction
{
   public static void Main()
   {
      Action<string> messageTarget; 

      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = delegate(string s) { ShowWindowsMessage(s); };
      else
         messageTarget = delegate(string s) { Console.WriteLine(s); };

      messageTarget("Hello, World!");
   }

   private static void ShowWindowsMessage(string message)
   {
      MessageBox.Show(message);
   }
}
using System;

public class ExampleFunc
{
   public static void Main()
   {
      Func<string, string> countLetters= delegate(int s)
         { return s.Lenght();}; 

      string name = "Dakota";
      Console.WriteLine(countLetters(name));
   }
}

Como ejercicio facilito ¿Que muestra por pantalla el siguiente ejemplo?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

static class Func
{
   static void Main(string[] args)
   {
      // Declare a Func variable and assign a lambda expression to the
      // variable. The method takes a string and converts it to uppercase.
      Func<string, string> selector = str => str.ToUpper();

      // Create an array of strings.
      string[] words = { "orange", "apple", "Article", "elephant" };
      // Query the array and select strings according to the selector method.
      IEnumerable<String> aWords = words.Select(selector);

      // Output the results to the console.
      foreach (String word in aWords)
         Console.WriteLine(word);
   }
}

Mostrar solución »

ORANGE
APPLE
ARTICLE
ELEPHANT

Enlaces:
Action Delegate MSDN
Func Delegate MSDN

Random Posts


Leave a Reply