当前位置:网站首页>C # - delegate detailed usage
C # - delegate detailed usage
2022-08-11 00:58:00 【Really fine duck】
什么是委托
A delegate is a function referenceObject,In fact, the function of the function pointer is completed with the class
C#中的委托(Delegate)类似于C或C++中函数的指针.委托(Delegate) 是存有对某个方法的引用的一种引用类型变量.引用可在运行时被改变.
委托(Delegate)特别用于实现事件和回调方法.所有的委托(Delegate)both derived 自System.Delegate 类.
委托的使用
1,声明委托:
Delegate void Print(int x)
2,初始化,给委托赋值
- 方法1:Print someFunc=hello;
- 方法2:Print someFunc=new Print(hello);
3,调用委托变量
SomeFunc(x);
委托的分类
- 委托静态方法:Delegate a static method
- 委托实例方法:Delegate an instance method
Principles of delegation
A delegate is a class that packages function pointers and instance objects together,它有两个重要的成员,One to hold the instance object,A pointer to hold the function.You can view it from the source codeSystem.Delegate
我们查看System.Delegate的属性,A property can be seenTarget
public Object Target
{
get
{
return GetTarget();
}
}
看一下GetTarget的功能
internal virtual Object GetTarget()
{
return (_methodPtrAux.IsNull())?_target:null;
}
This means that when a static method is given to a delegate, it will return onenull,If it is an instance method, will return the instance object where the current method is located(this)
下面用一段代码演示一下:
using System;
//声明委托
public delegate void Print();
namespace ConsoleApp1
{
public class Test
{
//实例方法
public void Test1()
{
Console.WriteLine("这是实例方法!");
}
//静态方法
public static void Test2()
{
Console.WriteLine("这是静态方法!");
}
}
class Program
{
static void Main(string[] args)
{
//委托的使用
Test t = new Test();//实例对象
Print p1 = new Print(t.Test1);//委托赋值-实例方法
p1();//调用委托
Print p2 = new Print(Test.Test2);//委托赋值-静态方法
p2();//调用委托
//委托原理
Console.WriteLine(p1.Target is Test);//实例方法-判断TargetDoes it point to the object where the method is located
Console.WriteLine(p2.Target is Test);//静态方法-判断Target是不是null
Console.ReadLine();
}
}
}
输出结果
这是实例方法!
这是静态方法!
True
False
也就是如果Target属性为nullDescription is a delegate of a static method,如果不为nullDescriptions are instance methods 委托
It should be noted that the declared delegate type must be consistent with the delegated function type and parameters,If the delegate did not return 值,Then the delegated function also has no return value,If the delegate has parameters,Then the delegated function and the delegated one 参数类型要一致.
Through this code, you can clearly see the role of the delegate,It is to encapsulate the method in a delegate,The delegate object can then be passed to code that can call the referenced method,It is not necessary to know at compile time which method will be called.
系统内置委托
The front is the delegate defined by yourself,But the system also provides two kinds of delegation:Action和Func,Actionfor not required The delegate to return a value to,FuncSuitable for delegates that need to return a value
Action委托
1,Action委托 封装一个方法,该方法不具有参数并且不返回值
2,Action<T>委托 封装一个方法,该方法只有一个参数并且不返回值
3,Action<T1,T2>委托 封装一个方法,The method has two parameters and returns no value
最多有16个参数
Func委托
1,Func(TResult)A delegate encapsulates a function that has no parameters but returns TResult The square of the value of the type specified by the parameter 法
2,Func(T,TResult)委托 封装一个具有一个参数并返回 TResult The square of the value of the type specified by the parameter法
3,Func(T1,T2,TResult)委托 封装一个具有两个参数并返回 TResult The square of the value of the type specified by the parameter 法
其中的T是参数类型,TResult是返回值类型
下面用一个例子演示:
using System;
namespace ConsoleApp1
{
public class Test
{
//Action示例
public void Test1()
{
Console.WriteLine("这是Action示例!");
}
//Func示例
public int Test2(int n)
{
return n;
}
}
class Program
{
static void Main(string[] args)
{
//The use of system built-in delegates
Test t = new Test();//实例对象
Action ac1=new Action(t.Test1);//委托赋值
ac1();//调用委托
Func<int,int> ac2 = new Func<int,int>(t.Test2);//委托赋值
Console.WriteLine(ac2(233));//调用委托
Console.ReadLine();
}
}
}
输出结果:
这是Action示例!
233
多播委托
多播委托是指在一个委托中注册多个方法,The plus operator can be used in delegates when registering methods
Or the minus operator to implement add or undo methods.
For example, the real ordering system,Can order sweets,面食,水果等,Entrusting here is equivalent to an ordering platform,每一 This type of commodity can be understood as a method of registering with the commissioner.
using System;
//声明委托
public delegate void Order();
namespace ConsoleApp1
{
public class Test
{
//买水果
public void Test1()
{
Console.WriteLine("购买水果!");
}
//Buy sweets
public static void Test2()
{
Console.WriteLine("Buy sweets!");
}
}
class Program
{
static void Main(string[] args)
{
//多播委托
Test t = new Test();//实例对象
Order order=new Order(t.Test1);//委托赋值-实例方法
order();//调用委托
Order order1 = new Order(Test.Test2);//委托赋值-静态方法
order1();
Console.ReadLine();
}
}
}
输出结果:
购买水果!
Buy sweets!
在使用多播委托时需要注意,The method parameter list registered in the delegate must match the parameter list defined by the delegate 相同,否则不能将方法添加到委托上.
如有错漏之处,敬请指正!
边栏推荐
- Use mysql statement to operate data table (table)
- 力扣------用栈操作构建数组
- "NIO Cup" 2022 Nioke Summer Multi-School Training Camp 3 DF Problem Solving
- postgresql参数意义
- "NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
- 【Video】Report Sharing | 2021 Insurance Industry Digital Insights
- Web APIs BOM - A Comprehensive Case of Operating Browsers
- 详解JDBC的实现与优化(万字详解)
- what is an array
- @Autowired注入RedisCache报错空指针
猜你喜欢
YOLOv5的Tricks | 【Trick12】YOLOv5使用的数据增强方法汇总
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 3 DF Problem Solving
③ 关系数据库标准语言SQL 数据查询(SELECT)
【ASM】字节码操作 ClassWriter COMPUTE_FRAMES 的作用 与 visitMaxs 的关系
word 设置标题前分页
Volatile和CAS
【C语言】探索数据的存储(整形篇)
C# using timer
池化技术有多牛?来,告诉你阿里的Druid为啥如此牛逼!
MSTP - Multiple Spanning Tree (Case + Configuration)
随机推荐
Mysql. Slow Sql
什么是“门”电路(电子硬件)
R language multiple linear regression, ARIMA analysis of the impact of different candidates in the United States on the economic GDP time series
循环单词
【Video】Report Sharing | 2021 Insurance Industry Digital Insights
SAP ABAP JSON 格式数据处理
16. Sum of the nearest three numbers
WebView2 通过 PuppeteerSharp 实现RPA获取壁纸 (案例版)
91.(cesium之家)cesium火箭发射模拟
[21 Days Learning Challenge] Half Insertion Sort
Analysis of LENS CRA and SENSOR CRA Matching Problems
R语言多元线性回归、ARIMA分析美国不同候选人对经济GDP时间序列影响
vim简单保存窗口标识
BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection Paper Notes
Linux install redis database
YOLOv5的Tricks | 【Trick11】在线模型训练可视化工具wandb(Weights & Biases)
Mysql database installation and configuration detailed tutorial
HW-常见攻击方式和漏洞原理(2)
成功解决raise TypeError(‘Unexpected feature_names type‘)TypeError: Unexpected feature_names type
Web APIs BOM - A Comprehensive Case of Operating Browsers