C # select and sort out key points of knowledge 11 entrustment and events (recommended Collection)

Posted by sean72 on Sat, 18 Dec 2021 21:48:20 +0100

1. Concept of entrustment

Entrustment is literally an agent, similar to a housing intermediary. The lessee entrusts the intermediary to lease the house for him.

In C# language, delegation delegates a method to implement specific functions.

Characteristics of entrustment:

1. A delegate is a reference type. Although it is somewhat similar to a method when defining a delegate, it cannot be called a method.

2. In terms of data structure, delegate is a user-defined type like class.

3. A delegate is an abstraction of a method. It stores the addresses of a series of methods with the same signature and return type.

4. When a delegate is called, all the methods contained in the delegate will be executed.

Classification of entrustment:

  • Method delegation

  • Multicast delegation

  • anonymous delegate

Use steps of delegation:

1. Define declarative delegation

2. Instantiate delegate

3. Call delegate

2. Method entrustment

Method delegate is the most commonly used delegate, and its defined syntax form is:

Modifier  delegate Return value type delegate name(parameter list);
1. Definition declaration delegation

From the above definition, we can see that the definition of delegate is similar to that of method. For example, define a delegate without parameters:

public delegate void MyDelegate();
2. Instantiate delegation

After defining the delegate, the step of instantiating the delegate is reached. When instantiating the delegate, the named method delegate must bring in the specific name of the method.

Syntax form of instantiation delegate

Delegate name delegate object name = new Delegate name(Method name);

The method name passed in the delegate can be either the name of a static method or the name of an 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. Call delegation

After instantiating the delegate, the delegate can be called in the syntax form

Delegate object name(parameter list);

Here, the parameters passed in the parameter list are the same as those defined by the delegate.

Example:

Add member method in Student class

//Studnet.cs
public void ShowInfo(string info)
{
    Console.WriteLine("{0}:\n{1}",info,this.Tostring());
}

Modify Program class

class Program
{
    //1. Define delegation
    public delegate void TestDelegate(string info);
    
        static void Main(string[] args)
        {
            Student stu = new Student();
            
            //When a delegate is created, the ShowInfo method of the stu object is executed by the delegate testDel.
            TestDelegate testDel = new TestDelegate(stu.ShowInfo);
            
            //Call delegate
            testDel("Entrusted test");
        }
    }

3. Multicast delegation

In C# language, multicast delegate refers to registering multiple methods in a delegate. When registering methods, you can use the plus or minus operator in the delegate to add or revoke methods.

For example, in the previous section, there is only one method in the testDel delegate. Then you can continue to add delegate methods through the plus or minus operator. When the delegate is executed, all delegated methods will be executed.

give an example:

Add two student classes and delegate their ShowInfo methods to testDel.

Modify Program class:

class Program
{
    //1. Define delegation
    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 delegate
        TestDelegate testDel = new TestDelegate(stu.ShowInfo);
        
        //Add delegate method
        testDel += stu1.ShowInfo;
        testDel += stu2.ShowInfo;
        
        //Call delegate
        testDel("Entrusted test");
        
        
        //Remove delegation method
        testDel -= stu2.ShowInfo;
        
        //Call delegate
        testDel("remove stu2 Entrusted test of");
    }
}

be careful:

When using a multicast delegate, it should be noted that the method parameter list registered in the delegate must be the same as the parameter list defined by the delegate, otherwise the method cannot be added to the delegate

4. Anonymous entrustment

In C# language, anonymous delegation refers to registering on the delegation using anonymous methods. In fact, it implements the role of delegation by defining code blocks in the delegation.

Specific grammatical forms

//Define delegate
 Modifier  delegate Return value type delegate name(parameter list);

//2. Define anonymous delegation
 Delegate name delegate object = delegate
{
    //Code block
};

//3. Call anonymous delegation
 Delegate object name(parameter list);

You can complete the definition and calling of anonymous delegation through the above three steps. It should be noted that after the code block is defined, a semicolon should be added after {}.

Example:

class Program
{
    //1. Define delegate
     public delegate void TestDelegate(string info);
    
    static void Main(string[] args)
    {
        Student stu = new Student(1, "Zhang San", 18);
        
        //Create delegate
        TestDelegate testDel = stu.ShowInfo;
        
        //Bind anonymous delegate
        testDel = delegate (string info)
        {
            Console.WriteLine("{0}\n{1}", info, "anonymous delegate ");
         Console.WriteLine("External variables used in anonymous delegates:\n{0}", stu); 
        };
        
         //Call delegate
        testDel("Entrusted test");
    }
}

Use anonymous delegates in generic collections

class Program
{
    static void Main(string[] args)
    {
        //Create a generic list in which the element type 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 sorting:");
            
        //Sort using anonymous delegates
        stuList.Sort(delegate(Student s1,Student s2)
        {
          	return s2.age ‐ s1.age;               
        });
        
        //Traverse and output
        foreach (var stu in stuList)
        {
            Console.WriteLine(stu);
        }
    }
}

5. Events

In C# language, Windows application, ASP Net website programs and other types of programs are inseparable from the application of events.

For example, when logging in to QQ software, you need to enter the user name and password, and then click the "login" button to log in to QQ. At this time, the action of clicking the button will trigger a button click event to complete the execution of the corresponding code to realize the login function.

An event is a reference type and is actually a special delegate.

Generally, each event will generate the sender and receiver. The sender refers to the object that causes the event, and the receiver refers to acquiring and processing the event. Events are used with delegates.

The syntax of event definition is as follows:

Access modifier  event Delegate name event name ; 

Here, because delegates are used in events, you need to define delegates before defining events.

After defining the event, you need to define the method used by the event and call the delegate through the event.

Examples are as follows:

For example, there are two teachers in a school, and each teacher has three students. Every time the teacher calls the roll, the students have to output their own information. In this example, the teacher's roll call can be regarded as an event. When the roll call event is triggered, the students will output their own information. The teacher is the sender of the event and the student is the receiver of the event

//Teacher.cs

/// <summary> 
///Teacher class 
/// </summary>
class Teacher
{
    //Define delegate type
    private delegate void CheckStudentDelegate(string action);
    
    //Create delegate event
    private event CheckStudentDelegate CheckStudentEvent;
    
    public Teacher(string name)
    {
        this.name = name;
    }
    
    public string name;
    
    public void BindingStudent(Student stu)
    {
        //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 and event bound methods
        CheckStudentEvent("");
    }
}
//The Student class refers to the previous code example
class Program
{
    static void Main(string[] args)
    {
        //Founding 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 operation
        teacherLi.CheckStudent();
        teacherWang.CheckStudent();
    }
}

6. Timer in C #

The Timer class is generally used for the timing function in C # and the Timer class needs to refer to the namespace using system Timers.

The Timer class contains two constructor methods

//Default construction method without parameters
Timer timer = new Timer();

//Construction method with one parameter. The parameter interval represents the timer interval, and the value range is 0 ‐ 2 ^ 31 ‐ 1
Timer timer = new Timer(1000);

Common methods or properties in the Timer class

Method or propertyeffect
AutoResetbool type: true: execute until Stop is called. (default); false: execute only once
IntervalTimer trigger interval, unit: ms (milliseconds)
Enabledbool type: true: timer starts; false: the timer stops
ElapsedEvent type. Can be bound to the method to trigger.
void Start();Start the timer. Equivalent to Enabled=true
void Stop();Stop the timer. Equivalent to Enabled=false

Example:

class Program
{
    static void Main(string[] args)
    {
        //Create a timer and execute it every 1000ms
        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: always)
        //timer.AutoReset = false;
        //Set the status of the timer (true: start, fasle: stop)
        timer.Enabled = true;
        Console.Read();
    }
    
    /// <summary> 
    ///Timing function, bound with 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);
    }
}

Topics: C#