C#之delegate

delegate 委托的使用:

封装一个方法,该方法只有一个参数并且不返回值。

using System;
using System.Windows.Forms; delegate void DisplayMessage(string message); public class TestCustomDelegate
{
public static void Main()
{
DisplayMessage messageTarget; if (Environment.GetCommandLineArgs().Length > )
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine; messageTarget("Hello, World!");
} private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
using System;
using System.Windows.Forms; public class TestAction1
{
public static void Main()
{
Action<string> messageTarget; if (Environment.GetCommandLineArgs().Length > )
messageTarget = ShowWindowsMessage;
else
messageTarget = Console.WriteLine; messageTarget("Hello, World!");
} private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
using System;
using System.Windows.Forms; public class TestAnonMethod
{
public static void Main()
{
Action<string> messageTarget; if (Environment.GetCommandLineArgs().Length > )
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;
using System.Windows.Forms; public class TestLambdaExpression
{
public static void Main()
{
Action<string> messageTarget; if (Environment.GetCommandLineArgs().Length > )
messageTarget = s => ShowWindowsMessage(s);
else
messageTarget = s => Console.WriteLine(s); messageTarget("Hello, World!");
} private static void ShowWindowsMessage(string message)
{
MessageBox.Show(message);
}
}
using System;
using System.Collections.Generic; class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard"); // Display the contents of the list using the Print method.
names.ForEach(Print); // The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
} private static void Print(string s)
{
Console.WriteLine(s);
}
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
上一篇:定时备份服务器数据库(借助windows任务计划以及mysqldump)


下一篇:来自 Google 的 R 语言编码风格指南