Action<T1, T2>委托

封装包含两个参数的方法委托,没有返回值。

语法

public delegate void Action<in T1, in T2>(
    T1 arg1,
    T2 arg2
)

类型参数

in T1:委托封装方法的第一个参数类型,此类型参数逆变。

用法

可以使用Action<T1, T2>委托以参数形式传递方法,而不用自定义委托。封装的方法必须与此委托的方法签名一致。也就是说,封装的方法也要有两个参数,没有返回值。

下面显式声明了一个名为ConcatStrings的委托。然后,它将两个方法中的任意一个的引用分配给其委托实例。其中一个方法将两个字符串写入控制台;另一个将两个字符串写入文件。

using System;
using System.IO;

delegate void ConcatStrings(string string1, string string2);

public class TestDelegate
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      ConcatStrings concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = WriteToFile;
      else
         concat = WriteToConsole;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}

下面以Action<T1, T2>委托简化上面的代码:

using System;
using System.IO;

public class TestAction2
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = WriteToFile;
      else
         concat = WriteToConsole;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}

其实就是预先定义好的委托,不需要自定义对应参数的委托了。

还可以同匿名方法一起使用:

using System;
using System.IO;

public class TestAnonymousMethod
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = delegate(string s1, string s2) { WriteToFile(s1, s2); };
      else
         concat = delegate(string s1, string s2) { WriteToConsole(s1, s2);} ;

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}

也可以将匿名函数替换为lambda表达式:

using System;
using System.IO;

public class TestLambdaExpression
{
   public static void Main()
   {
      string message1 = "The first line of a message.";
      string message2 = "The second line of a message.";
      Action<string, string> concat;

      if (Environment.GetCommandLineArgs().Length > 1)
         concat = (s1, s2) => WriteToFile(s1, s2);
      else
         concat = (s1, s2) => WriteToConsole(s1, s2);

      concat(message1, message2);
   }

   private static void WriteToConsole(string string1, string string2)
   {
      Console.WriteLine("{0}\n{1}", string1, string2);
   }

   private static void WriteToFile(string string1, string string2)
   {
      StreamWriter writer = null;
      try
      {
         writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false);
         writer.WriteLine("{0}\n{1}", string1, string2);
      }
      catch
      {
         Console.WriteLine("File write operation failed...");
      }
      finally
      {
         if (writer != null) writer.Close();
      }
   }
}

后两者都没有起到简化代码的作用。

时间: 2024-08-08 06:11:38

Action<T1, T2>委托的相关文章

C# 通过Action委托提高代码的重用

如何通过Action重复的代码 其实提高代码的重用,有几个途径 a.继承 b.工具方法 c.使用委托 a,b两点都很容易理解,说一下"c"这一点,举个DataContext事务的例子 using(var context = new DataContext()) { context .BeginTransaction(); try { context.User.GetUser(); context.User.add(new User{name="xian"}); co

委托、Lambda表达式、事件系列05,Action委托与闭包

来看使用Action委托的一个实例: static void Main(string[] args) { int i = 0; Action a = () => i++; a(); a(); Console.WriteLine(i); } 结果是期望能的2.但令人好奇的是:栈上的变量i是如何传递给Action委托的? 反编译进行查看,首先看Main方法对应的IL代码: 再看c_DisplayClass1的IL代码: 从中可以看出:→在托管堆上创建了一个名为c_DisplayClass1的实例→把

复习action委托

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { public static class InvokeExt { //扩展方法进行装箱输出继承IEnumerable<T>的内容项 public static void ShowItems<T>

Action委托

封装一个方法,该方法不具有参数并且不返回值 public delegate void Action(); 在使用 Action 委托时,不必显式定义一个封装无参数过程的委托. 例如,以下代码显式声明了一个名为 ShowValue 的委托,并将对 Name.DisplayToWindow 实例方法的引用分配给其委托实例. using System; using System.Windows.Forms; public delegate void ShowValue(); public class

.NET : Func委托和Action委托

上一篇我们讲到了如何在ASP.NET页面中实现异步任务.我们来回顾一下里面一个特殊的类型:LongTimeTask public class LongTimeTask{    public string Result = string.Empty;    public HelloWorldHandler handler; public delegate string HelloWorldHandler();    public string HelloWorld()    {        Th

C#中常见的委托(Func委托、Action委托、Predicate委托)

今天我要说的是C#中的三种委托方式:Func委托,Action委托,Predicate委托以及这三种委托的常见使用场景. Func,Action,Predicate全面解析 首先来说明Func委托,通过MSDN我们可以了解到,Func委托有如下的5种类型: (1) *delegate TResult Func<TResult>(); (2)*delegate TResult Func<T1,TResult>(T1 arg1); (3) *delegate TResult Func&

Func 委托 和 Action 委托 初步谈论

继上篇EventHandler之后,继续填坑,简单了解下Func<TResult> 委托 和 Action 委托. msdn对于两者的解释: Func<TResult>:封装一个不具有参数但却返回 TResult 参数指定的类型值的方法. Action:封装一个方法,该方法不具有参数并且不返回值. 两者的区别在于:有无返回值. 至于 Func<T,TResult>.Func<T1,T2,TResult>.... Action<T>.Action&

Func 和 Action 委托

有了泛型委托,就有了一能适用于任何返回类型和任意参数(类型和合理的个数)的通用委托,Func 和 Action.如下所示(下面的in表示参数,out表示返回结果): delegate TResult Func <out TResult> ();delegate TResult Func <in T, out TResult> (T arg);delegate TResult Func <in T1, in T2, out TResult> (T1 arg1, T2 ar

C# 匿名方法 委托 Action委托 Delegate委托

原文地址:https://msdn.microsoft.com/zh-cn/library/bb882516.aspx 匿名函数是一个“内联”语句或表达式,可在需要委托类型的任何地方使用. 可以使用匿名函数来初始化命名委托,或传递命名委托(而不是命名委托类型)作为方法参数. C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式. 实例参考: 1 using System; 2 using System.Collection

使用Action委托协助添加/修改

Action Mc = () => { Model.Stuno = sStuno; Model.UserId = sUserId; Model.Pno = sPno; Model.Name = sName; Model.Gender = sGender; Model.Birthday = sBirthday; if (!string.IsNullOrWhiteSpace(sAge)) { Model.Age = int.Parse(sAge); } Model.Tel = sTel; Model