C#之delegate

时间:2023-03-09 04:33:11
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
*/