实例一:Action委托,以及泛型委托
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Show()
{
Console.WriteLine("打印输出1");
}
private static void Show(int i)
{
Console.WriteLine(i);
}
private static void Show(string str1, string str2)
{
Console.WriteLine(str1+str2);
}
public static void Main()
{
Action a = Show; //Action为系统内置的一个不带返回值且没有参数的委托
Action<int> a1 = Show; //Action<T>为一个不带返回值的泛型委托T为参数的类型
Action<string, string> a2=Show; //带两个参数的委托
a();
a1(1000);
a2("hehe","nihao");
}
}
实例二:Func委托
using System;
using System.Text;
using System.Text.RegularExpressions;
class Test
{
static void Show()
{
Console.WriteLine("打印输出1");
}
private static int Show(int i)
{
Console.WriteLine(i);
return 100;
}
private static string Show(string str1, string str2)
{
Console.WriteLine(str1+str2);
string str = "完成代码";
return str;
}
public static void Main()
{
Func<int, int> a; //Func也是系统定义的一个委托,第一个参数为函数参数,第二个参数为返回类型
a = Show;
Func<string, string, string> b; //能委托的函数带有两个string类型参数,以及一个string类型的返回值
b = Show;
Console.WriteLine(a(1000));
Console.WriteLine(b("代码1","代码2"));
}
}
实例三:多播委托
using System;
using System.Text;
using System.Text.RegularExpressions;
internal class Employ
{
public int data;
public string name;
public Employ(int d, string n)
{
data = d;
name = n;
}
}
class Test
{
static void Show()
{
Console.WriteLine("打印输出1");
}
private static void Show2()
{
Console.WriteLine("show2");
}
private static int Show(int i)
{
Console.WriteLine(i);
return 100;
}
private static string Show(string str1, string str2)
{
Console.WriteLine(str1+str2);
string str = "完成代码";
return str;
}
public static void Main()
{
Action a;
a = Show;
a += Show2;
Delegate[]delegates=a.GetInvocationList(); //多播委托获取所有指向的函数列表
foreach (var v in delegates)
{
v.DynamicInvoke(); //单独调用函数
}
}
}
实例四:使用泛型委托来对类对象排序
using System;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
internal class Employ
{
public int data;
public string name;
public Employ(int d, string n)
{
data = d;
name = n;
}
public static bool Compare(Employ a, Employ b) //自定义的比较函数
{
if (a.data > b.data)
return true;
else
{
return false;
}
}
public override string ToString() //重载原类的ToSting方法,用于输出时直接输出
{
return data + ":" + name;
}
}
internal class Test
{
private static void sort<T>(T [] a,Func<T,T,bool>comp ) //使用泛型委托来实现对对象冒泡排序
{
for (int i = 0; i < a.Length-1; i++)
{
for (int j = 0; j < a.Length-i-1; j++)
{
if (comp(a[j] ,a[j + 1])) //调用委托
{
T temp = a[j]; //这里其实交换的是数组中的每个对象的引用,相当于c++指针数组中的指针
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
public static void Main()
{
Employ[] a =
{
new Employ(10, "a"),
new Employ(3, "b"),
new Employ(2, "c"),
new Employ(5, "d"),
new Employ(4, "d")
};
sort<Employ>(a, Employ.Compare); //调用排序
foreach (var w in a)
{
Console.WriteLine(w);
}
}
}
c#中委托补充(实例学习)
最新推荐文章于 2024-05-28 17:38:57 发布