当前位置:网站首页>C # carefully sorting out key points of knowledge 11 entrustment and events (recommended Collection)
C # carefully sorting out key points of knowledge 11 entrustment and events (recommended Collection)
2022-07-25 15:27:00 【꧁ small ۣۖ Pigeon ۣۖ Puzi ۣۖ ิ꧂】
1. The concept of delegation
Entrustment is literally an agent , Similar to housing agency , The tenant entrusts an intermediary to rent the house for him .
stay C# In language , Delegation delegates a method to implement a specific function .
The characteristics of the Commission :
1、 A delegate is a reference type , Although it is somewhat similar to the method when defining delegates , But it can't be called a method .
2、 In terms of data structure , Delegation is a user-defined type just like class .
3、 A delegate is an abstraction of a method , A method that has the same type as the one that stores the signature .
4、 When calling a delegate , All methods contained in the delegate will be executed .
The classification of delegation :
Method Commission
The multicast delegate
Anonymous delegate
Use steps of delegation :
1、 Define a declaration delegate
2、 Instantiation delegation
3、 The delegate
2. Method Commission
Method delegation is the most commonly used kind of delegation , The grammatical form of its definition :
Modifier delegate return type Name of Commission ( parameter list );
1. Define a declaration delegate
As you can see from the above definition , The definition of delegate is similar to that of method . For example, define a delegate without parameters :
public delegate void MyDelegate();
2. Instantiation delegation
After defining the delegate, the step of instantiating the delegate is reached , When a named method delegate instantiates a delegate, the specific name of the method must be brought in .
Instantiate the syntax form of the delegate
Name of Commission Delegate object name = new Name of Commission ( Method name );
The method name passed in the delegate can be either the name of a static method , It can also be the name of the instance method .
It should be noted that , The method name written in the delegate must be the same as the return value type and parameter list when the delegate is defined
3. The delegate
After instantiating the delegate, you can call the delegate , Grammatical form
Delegate object name ( parameter list );
ad locum , The parameters passed in the parameter list are the same as those defined by the delegate .
example :
stay Student New member method in class
//Studnet.cs
public void ShowInfo(string info)
{
Console.WriteLine("{0}:\n{1}",info,this.Tostring());
}
modify Program class
class Program
{
//1. Define the entrusted
public delegate void TestDelegate(string info);
static void Main(string[] args)
{
Student stu = new Student();
// Create delegation ,stu Object's ShowInfo The method is entrusted to testDel To carry out .
TestDelegate testDel = new TestDelegate(stu.ShowInfo);
// The delegate
testDel(" Commission test ");
}
}
3. The multicast delegate
stay C# In language, multicast delegate refers to registering multiple methods in a delegate , When registering a method, you can use the plus or minus operator in the delegate to add or revoke the method .
For example, in the previous section testDel There is only one method in a delegate . Then you can continue to add delegate methods through the plus or minus operator , So when the execution is entrusted , All delegated methods will be executed .
give an example :
Two new student classes , And its ShowInfo Methods are delegated to testDel.
modify Program class :
class Program
{
//1. Define the entrusted
public delegate void TestDelegate(string info);
static void Main(string[] args)
{
Student stu = new Student(1," Xiao Zeng ",19);
Student stu1 = new Student(2," Xiaojia ",19);
Student stu2 = new Student(3," Xiaoyi ",19);
// Create delegation
TestDelegate testDel = new TestDelegate(stu.ShowInfo);
// Add delegate method
testDel += stu1.ShowInfo;
testDel += stu2.ShowInfo;
// The delegate
testDel(" Commission test ");
// Remove delegation method
testDel -= stu2.ShowInfo;
// The delegate
testDel(" Remove stu2 Entrusted test of ");
}
}
Be careful :
When using multicast delegation, you should pay attention to , The method parameter list registered in the delegate must match the parameter list defined by the delegate Same as , Otherwise, you cannot add a method to a delegate
4. Anonymous delegate
stay C# Anonymous delegation in language refers to the use of anonymous methods to register on the delegation , In fact, the role of delegation is realized by defining code blocks in delegation .
Specific grammatical forms
// Define the entrusted
Modifier delegate return type Name of Commission ( parameter list );
//2. Define anonymous delegates
Name of Commission Delegate object = delegate
{
// Code block
};
//3. Call anonymous delegate
Delegate object name ( parameter list );
Pass above 3 The definition and invocation of anonymous delegates can be completed in three steps , It should be noted that , After defining the code block of anonymous delegation, you should {} Followed by a semicolon .
example :
class Program
{
//1、 Define the entrusted
public delegate void TestDelegate(string info);
static void Main(string[] args)
{
Student stu = new Student(1, " Zhang San ", 18);
// Create delegation
TestDelegate testDel = stu.ShowInfo;
// Bind anonymous delegates
testDel = delegate (string info)
{
Console.WriteLine("{0}\n{1}", info, " Anonymous delegate ");
Console.WriteLine(" Use external variables in anonymous delegates :\n{0}", stu);
};
// The delegate
testDel(" Commission test ");
}
}
Anonymous delegates are used in generic collections
class Program
{
static void Main(string[] args)
{
// Create a generic list , The element type in the list is Student
List<Student> stuList = new List<Student>();
// Add three elements to the element
stuList.Add(new Student(3, " Zhang San ", 20));
stuList.Add(new Student(1, " Li Si ", 15));
stuList.Add(new Student(2, " Wang Wu ", 18));
// Traverse and output
foreach (var stu in stuList)
{
Console.WriteLine(stu);
}
Console.WriteLine(" After ordering :");
// Use anonymous delegates to complete sorting
stuList.Sort(delegate(Student s1,Student s2)
{
return s2.age ‐ s1.age;
});
// Traverse and output
foreach (var stu in stuList)
{
Console.WriteLine(stu);
}
}
}
5. event
stay C# In language ,Windows Applications 、 ASP.NET Website programs and other types of programs are inseparable from the application of events .
For example, when logging in QQ The user name and password are required for software , And then click “ Sign in ” Button to log in QQ, At this point, the action of clicking a button will trigger a button click event to complete the execution of the corresponding code to realize the login function .
Event is a reference type , In fact, it is also a special kind of entrustment .
Usually , Every event will produce sender and receiver , The sender refers to the object that raises the event , Receiving party refers to obtaining 、 Handling events . Events are used with delegates .
The syntax of event definition is as follows :
Access modifier event Name of Commission Event name ;
ad locum , Because a delegate was used in the event , Therefore, you need to define the delegate before defining the event .
After defining the event, you need to define the method used by the event , And invoke the delegate through the event .
Examples are as follows :
For example, there are two teachers in a school , Every teacher has three students . Every time the teacher calls the roll, the students have to output their own information . Then in this example, the teacher roll call can be regarded as an event , When the roll call event is triggered , Students will output their own information . The teacher is the sender of the event , The student is the receiver of the event
//Teacher.cs
/// <summary>
/// The teacher class
/// </summary>
class Teacher
{
// Define delegate type
private delegate void CheckStudentDelegate(string action);
// Create a delegate event
private event CheckStudentDelegate CheckStudentEvent;
public Teacher(string name)
{
this.name = name;
}
public string name;
public void BindingStudent(Student stu)
{
// The binding event
CheckStudentEvent += stu.ShowInfo;
}
public void UnBindingStudent(Student stu)
{
// Unbind
CheckStudentEvent -= stu.ShowInfo;
}
public void CheckStudent()
{
Console.WriteLine("{0} Roll call :", name);
// Call event , Trigger the method bound to the event
CheckStudentEvent("");
}
}
//Student Class refer to the previous code example
class Program
{
static void Main(string[] args)
{
// Create a teacher, Professor Wang
Teacher teacherWang = new Teacher(" Professor Wang ");
// Bind three students to Professor Wang
teacherWang.BindingStudent(new Student(3, " Zhang San ", 20));
teacherWang.BindingStudent(new Student(1, " Zhang Yi ", 20));
teacherWang.BindingStudent(new Student(2, " Zhang Er ", 20));
// Founding teacher Professor Li
Teacher teacherLi = new Teacher(" Professor Li ");
// Bind three students to Professor Li
teacherLi.BindingStudent(new Student(4, " Bai Xiaosi ", 17));
teacherLi.BindingStudent(new Student(5, " Bai Xiaowu ", 17));
teacherLi.BindingStudent(new Student(6, " Bai Xiaoliu ", 17));
// Roll call
teacherLi.CheckStudent();
teacherWang.CheckStudent();
}
}
6.C# Timer in
C# The timer is generally used for the medium timing function Timer class ,Timer Class needs to reference namespace using System.Timers.
Timer Class contains two constructors
// Default construction method without parameters
Timer timer = new Timer();
// Construction method with one parameter , Parameters interval Represents the timer interval , Value range 0‐2^31‐1
Timer timer = new Timer(1000);
Timer Common methods or properties in classes
| Method or property | effect |
|---|---|
| AutoReset | bool type :true: Has been performed , until Stop call .( Default );false: Only once |
| Interval | Timer trigger interval , Company :ms( millisecond ) |
| Enabled | bool type :true: The timer starts ;false: The timer stops |
| Elapsed | Event type . It can be bound to the method to be triggered . |
| void Start(); | Start timer . Equivalent to Enabled=true |
| void Stop(); | Stop timer . Equivalent to Enabled=false |
example :
class Program
{
static void Main(string[] args)
{
// Create a timer , every other 1000ms Do it once
Timer timer = new Timer(1000);
// Set the trigger event of the timer
timer.Elapsed += Timer_Elapsed;
// Set the execution times of the timer (false: once true: Has been performed )
//timer.AutoReset = false;
// Set the status of the timer (true: start-up ,fasle: stop it )
timer.Enabled = true;
Console.Read();
}
/// <summary>
/// Timing function , Bound to timer events
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Timer_Elapsed(object sender,ElapsedEventArgs e)
{
Console.WriteLine("sender Type:{0}",sender.GetType());
Console.WriteLine("Signal Time:{0}",e.SignalTime);
}
}
边栏推荐
- CF566A-贪心+字典树
- How to finally generate a file from saveastextfile in spark
- Qtime定义(手工废物利用简单好看)
- 带你详细认识JS基础语法(建议收藏)
- C # fine sorting knowledge points 10 generic (recommended Collection)
- 为什么PrepareStatement性能更好更安全?
- ICPC2021昆明M-暴力+主席树
- Submarine cable detector tss350 (I)
- 数据系统分区设计 - 请求路由
- Simulate setinterval timer with setTimeout
猜你喜欢
随机推荐
单例模式3--单例模式
matlab---错误使用 var 数据类型无效。第一个输入参数必须为单精度值或双精度值
Remember that spark foreachpartition once led to oom
Recommend 10 learning websites that can be called artifact
JVM-垃圾收集器详解
JVM dynamic bytecode technology details
异步fifo的实现
In depth: micro and macro tasks
《图书馆管理系统——“借书还书”模块》项目研发阶段性总结
Args parameter parsing
小波变换--dwt2 与wavedec2
2021HNCPC-E-差分,思维
Reflection - Notes
UIDocumentInteractionController UIDocumentPickerViewController
Iframe nested other website page full screen settings
Yan required executor memory is above the max threshold (8192mb) of this cluster!
Solve the timeout of dbeaver SQL client connection Phoenix query
伤透脑筋的CPU 上下文切换
<栈模拟递归>
ML - 自然语言处理 - 基础知识









