自定义 无参无返回值 委托
using System;
namespace ConsoleApp5
{
delegate void MyDele();
class Program
{
static void Main(string[] args)
{
MyDele dele1 = new MyDele(M1);
dele1 += (new Student()).SayHello;
dele1.Invoke();
}
static void M1()
{
Console.WriteLine("M1 is Called");
}
class Student
{
public void SayHello()
{
Console.WriteLine("Hello C#");
}
}
}
}
自定义 有参有返回值 委托
using System;
namespace ConsoleApp5
{
delegate int MyDele(int a, int b);
class Program
{
static void Main(string[] args)
{
MyDele myDele = new MyDele(Add);
int result = myDele(100, 200);
Console.WriteLine(result);
}
static int Add(int x, int y)
{
return x + y;
}
}
}
自定义 泛型 委托
using System;
namespace ConsoleApp5
{
delegate T MyDele<T>(T a, T b);
class Program
{
static void Main(string[] args)
{
MyDele<int> deleAdd = new MyDele<int>(Add);
int addResult = deleAdd(100, 200);
Console.WriteLine(addResult);
MyDele<double> deleMul = new MyDele<double>(Mul);
double mulResult = deleMul(100, 200);
Console.WriteLine(mulResult);
Console.WriteLine(deleAdd.GetType().IsClass);
}
static int Add(int x, int y)
{
return x + y;
}
static double Mul(double x, double y)
{
return x * y;
}
}
}
c# 类库 预先声明好的泛型委托
没有返回值类型 Action
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Action action = new Action(M1);
action.Invoke();
Action<string> action2 = new Action<string>(SayHello);
action2("ll");
Action<string, int> action3 = new Action<string, int>(sayCountHello);
action3("LL", 3);
}
static void M1()
{
Console.WriteLine("M1 is called");
}
static void SayHello(string name)
{
Console.WriteLine($"Hello,{name}!");
}
static void sayCountHello(string name, int count)
{
for (int i = 0; i < count; i++)
{
Console.WriteLine($"Hello,{name}");
}
}
}
}
有返回值类型 Func
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Func<int, int, int> func = new Func<int, int, int>(Add);
int result = func(100, 200);
Console.WriteLine(result);
Func<double, double, double> func2 =
new Func<double, double, double>(Mul);
double resultMul = func2(10, 20);
Console.WriteLine(resultMul);
}
static int Add(int x, int y)
{
return x + y;
}
static double Mul(double x, double y)
{
return x * y;
}
}
}