C# 委托的不同声明方式,简化及泛型委托的优势
委托是 c#中比较重要的内容,
1、其可以做为事件的基础,
2、在对象方法之间的间接调用
3、委托声明中添加Lambda表达式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp_DelegateWithGeneric
{
// 声明一个无返回值有参数的委托,注意在声明委托参数时分配参数名称.委托声明前面不必加修饰符
delegate void MyDele(string str);
// 声明一个带返回值带参数的委托,注意在声明委托参数时分配参数名称
delegate int MyDele_int(int x, int y);
// 声明一个带返回值带参数的泛型委托,泛型委托没有明确返回值及参数的类型,但是在之后声明实例时需要明确
delegate T MyDele_Generic<T>(T x, T y);
internal class Program
{
static void Main(string[] args)
{
Student student = new Student();
MyDele myDele = new MyDele(student.SayHello);
MyDele_int myDele_int = new MyDele_int(student.Add);
// 注意泛型委托在创建实例时需要明确返回值类型及符合此委托要求的方法
MyDele_Generic<int> myDele_Generic = new MyDele_Generic<int>(student.Add);
// 由于泛型委托没有在声明时明确类型,在创建实例时可以通过配置类型来创建不同返回值类型的委托实例
MyDele_Generic<float> myDele_Generic_float = new MyDele_Generic<float>(student.mul);
// 对于上述的自定义委托其实C#系统已经自带了能够满足要求的委托类型,如下是无返回值但可以带参数的Action委托
Action<string> myAction1 = new Action<string>(student.SayHello);
// 对于委托类型可以将前面的声明省略掉,替换为var,保留后面NEW的委托约束
var myAction2 = new Action<string>(student.SayHello);
// 如下是可以带参数及返回值的Func委托
Func <int,int,int> myFunc1 = new Func<int, int, int>(student.Add);
// 通过lambda表达式来生成函数作为委托的参数
var myFunc2 = new Func<int, int, int>((int a, int b) => { return a + b; });
// 由于委托里已经限制了输入参数的类型,lambda表达式里的参数类型声明可以省略
var myFunc3 = new Func<int, int, int>((a,b) => { return a + b; });
// 也可以通过声明委托的类型在之后的表达式中直接使用Lambda
Func<int, int, int> myFunc4 = (a, b) => { return a + b;};
myDele("World");
int x = 10;
int y = 20;
int result = 0;
float f1 = 3.5F;
float f2 = 4.5F;
float f_resutl = 0;
result = myDele_int(x, y);
Console.WriteLine(result);
result = myDele_Generic(x, y);
Console.WriteLine(result);
f_resutl = myDele_Generic_float(f1, f2);
Console.WriteLine(f_resutl);
Console.WriteLine("Follow is using system define delegate");
myAction1("World");
myAction2("World");
result = myFunc1(x, y);
Console.WriteLine(result);
result = myFunc2(10, 23);
Console.WriteLine(result);
result = myFunc3(14, 37);
Console.WriteLine(result);
result = myFunc4(22, 73);
Console.WriteLine(result);
// 声明了泛型方法的实例,一个泛型方法中包含泛型委托(Lambda表达式)及泛型参数
Calculate<int>((int a, int b) => { return a * b; },10,20);
// 简化泛型方法的声明将可以通过Lambda参数的类型来推断出前面的类型,所以可以省略掉
Calculate((a, b) => { return a * b; }, 10, 20);
Console.ReadLine();
}
// 声明了一个泛型方法,其中参数中包含泛型委托,泛型参数
static void Calculate<T> (Func<T,T,T> func,T x,T y)
{
T restult = func(x, y);
Console.WriteLine(restult);
}
}
class Student
{
public void SayHello(string name)
{
Console.WriteLine("Hello {0}!", name);
}
public int Add(int x, int y)
{
return x + y;
}
public float mul(float x, float y)
{
return x * y;
}
}
}
总结
本段代码是根据刘铁锰老师在委托一课中仿写的,其中加一一些个人的见解及代码注释,更详细的内容请搜索刘铁猛老师的相关视频。
祝你好好学习,天天向上!