Home Backend Development C#.Net Tutorial C# delegate and event explanation

C# delegate and event explanation

Dec 14, 2016 am 11:17 AM

From the preface, you should have some understanding of the importance of commissions and events. Although we can still be vague about it now, from my vernacular series, I will make these concepts easy to understand. First of all, let’s talk about delegation. Literally understood, all Chinese people should know this meaning, unless they don’t recognize the two Chinese characters for delegation. For example, Xiao Ming entrusts Xiao Zhang to buy a ticket.

But in our programming world, is it also so simple? Of course, what is OO? OO is the abstraction of the real world. All things in the real world can be well interpreted in OO. Sorry, I am going too far...

Then let’s get straight to the point. If students are not bored, you can take a look at the GreetingPeople example in Chinese and English on the Internet.

                                                                                                                                                                                                                                   out out over terresence to the C# syntax

public delegate void BugTicketEventHandler();
Copy after login

    out  . Cultivation】

It’s over, this is delegation, it’s that simple, let’s see what’s the difference from our normal method?

public void BuyTicket()
{   
 方法体
 }
Copy after login

You know the difference? In real life, a delegate is just a command, and someone else does the work. But in the programming world, the delegate just stores the address of each method, and he himself does nothing.

So let’s take the real-life scene where Xiao Ming entrusted Xiao Zhang to buy a ticket. How can it be reflected in the program world?

代码 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->//小张类
    public class MrZhang
    {
        //其实买车票的悲情人物是小张
        public static void BuyTicket()
        {
            Console.WriteLine("NND,每次都让我去买票,鸡人呀!");
        }
    }

    //小明类
    class MrMing
    {
        //声明一个委托,其实就是个“命令”
        public delegate void BugTicketEventHandler();

        public static void Main(string[] args)
        {
            //这里就是具体阐述这个命令是干什么的,本例是MrZhang.BuyTicket“小张买车票”
            BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);

            //这时候委托被附上了具体的方法
            myDelegate();
            Console.ReadKey();
        }
    }
Copy after login

BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);

This is the declaration method of the delegate, BugTicketEventHandler (delegated method); the delegated method must be added because the delegated constructor is not empty.

Note: The parameters and return type of the delegate must be consistent with the method you want to delegate. For example:

public delegate void BugTicketEventHandler();


public static void BuyTicket()
{
Console.WriteLine( "NND, let me buy tickets every time, chicken man!");
}

Students, you can digest this and take a break. Let's briefly talk about the concept of delegation chain:

In fact, the delegation chain is also quite simple. In real life, after Xiao Ming asks Xiao Zhang to buy a ticket, he may then ask him to bring a movie ticket,

And the expression in our program world is:

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->//小张类
    public class MrZhang
    {
        //其实买车票的悲情人物是小张
        public static void BuyTicket()
        {
            Console.WriteLine("NND,每次都让我去买票,鸡人呀!");
        }

        public static void BuyMovieTicket()
        {
            Console.WriteLine("我去,自己泡妞,还要让我带电影票!");
        }
    }

    //小明类
    class MrMing
    {
        //声明一个委托,其实就是个“命令”
        public delegate void BugTicketEventHandler();

        public static void Main(string[] args)
        {
            //这里就是具体阐述这个命令是干什么的,本例是MrZhang.BuyTicket“小张买车票”
            BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);

            myDelegate += MrZhang.BuyMovieTicket;
            //这时候委托被附上了具体的方法
            myDelegate();
            Console.ReadKey();
        }
    }
Copy after login

In fact, we Just added myDelegate += MrZhang.BuyMovieTicket;

in the program
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add next-level C compiler How to add next-level C compiler Mar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

What are the alternatives to NULL in C language What are the alternatives to NULL in C language Mar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

Which C language compiler is better? Which C language compiler is better? Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language? Is NULL still important in modern programming in C language? Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers? What are the web versions of C language compilers? Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

Method of copying code by C language compiler Method of copying code by C language compiler Mar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

C language online programming website C language compiler official website summary C language online programming website C language compiler official website summary Mar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

C language compiler installation tutorial (computer version) C language compiler installation tutorial (computer version) Mar 03, 2025 pm 05:41 PM

This tutorial guides users through installing C compilers on Windows, macOS, and Linux. It details installation for popular compilers (MinGW, Visual Studio, Xcode, GCC), explains environment variable configuration, and offers troubleshooting steps

See all articles