Home > Backend Development > C#.Net Tutorial > C# Learning Diary 19----Reference Type of Delegate (Delegate) Type

C# Learning Diary 19----Reference Type of Delegate (Delegate) Type

黄舟
Release: 2017-01-21 15:11:48
Original
1708 people have browsed it

The meaning of the delegate type that represents (and delegates are also it) has been introduced in the preface to reference types (click to view), so I won’t go into details here. In short, a delegate is a class, which defines methods. The type allows the method to be passed as a parameter of another method. To put it bluntly, the method can be passed as a parameter. All delegates (Delegate) are derived from the System.Delegate class.

                                                                             HC555’s roommate HC555 is a LOL lover, and he also likes to shop on Taobao. When he was immersed in LOL, the courier called him to pick it up. Express delivery, the most annoying thing about playing games is this, so he asked me to take the express delivery back for him. At this time, we regard the roommate as a (roomfriend) class, and taking the express delivery is a method in the class (takepackage()), and I am an object instantiated by Delegate (an object that can carry methods), "carrying" the method of picking up express delivery from my roommate.

Declaration of a delegate:

The declaration of a delegate determines the methods that can be referenced by the delegate. A delegate can point to a method with the same label as it.

For example, declare a delegate:

    public delegate int MyDelegate(string str); //string类型的变量就是它的标签
Copy after login

The above delegate can be used to reference any method that takes a single string parameter and returns an int type variable.

Instantiate a delegate:

The delegate is the type of the method. Once the delegate type is declared, the delegate object must be created using the new keyword and must be used with the new keyword. related to a specific method. When creating a delegate, methods are passed to the new statement as variables, but without parameters. For example:

  public delegate int MyDelegate(string str);  //委托的声明
           .....   
           public static int Add(string s);   //定义的一个方法
         .....   
         MyDelegate my = new MyDelegate(Add) ;  //实例化一个委托,其实就是实例化一个对象
Copy after login

Code example:

Back to the original story of picking up the express delivery, we convert this story into code:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{   
    public delegate void MyDelegate(string str);    //委托的声明  
  
    class roomfriend  //定义室友这个类  
    {   
        public static void takepackage(string name)  //定义一个取快递的方法  
        {  
           Console.WriteLine("我叫 {0} 这是一个取快递方法",name);  
            
        }  
    }  
    class program  
    {  
        static void Main(string[] args)  
        {  
            MyDelegate myd = new MyDelegate(roomfriend.takepackage); //实例化一个委托“我”携带一个方法(将方法当参数传入)  
            myd("HC555");   //由我实现室友的方法,实际是室友的方法当参数传给了我  
        }  
    }  
}
Copy after login

The result is Like this:


C# Learning Diary 19----Reference Type of Delegate (Delegate) Type

When I returned to the dormitory after picking up the express delivery, my roommate called me and said he was hungry. I was asked to buy something to eat when I passed by the supermarket. In the spirit of Lei Feng, I agreed... "Buying something" here can also be seen as a method in roomfriend, and "I" "carry" another one from his method. In C#, use "+=" to connect the merge methods in sequence, and output them in sequence when called;

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{   
    public delegate void MyDelegate(string str);    //委托的声明  
  
    class roomfriend  //定义室友这个类  
    {   
        public static void takepackage(string name)  //定义一个取快递的方法  
        {  
           Console.WriteLine("我叫 {0} 这是一个取快递方法",name);  
            
        }  
        public static void shopping(string name)   //定义一个买东西的方法  
        {  
            Console.WriteLine("我叫 {0}  这是一个买东西的方法",name);  
        }  
      
    }  
    class program  
    {  
        static void Main(string[] args)  
        {  
            MyDelegate myd = new MyDelegate(roomfriend.takepackage); //实例化一个委托“我”携带一个方法(将方法当参数传入)  
            
            myd += roomfriend.shopping;    // += 合并运算顺序执行方法   
            myd("HC555");  
        }  
    }  
}
Copy after login

The results are as follows:

C# Learning Diary 19----Reference Type of Delegate (Delegate) Type

(Alas! I am not courier Have you taken it? Why else... 0.0)

In the above we use "+=" to connect the method. When we want to cancel a method, we can naturally use "-=" to cancel the connection with "I" Carry the relationship, so in the above code we only need to add myd -= roomfriend.takepackage // put it below += so that the method of taking express will not be called again.

I bought a few boxes of biscuits from the supermarket and my phone rang again. It was my roommate again. He told me that the package was for his girlfriend and asked me to deliver it to him. In the past, good people will stick to it, and I agreed to it. . When delivering a courier to her girlfriend, she was in a hurry so she hurriedly took away all my things, including the boxes of biscuits. . Then I laughed and returned to the dormitory happily... Here we define another (girlfriend) class, which has a method of accepting (accept), and I (delegate) is used as a parameter of the method;

Definition method: public static void accept(string name,MyDelegate pack); If you think of a delegate as a box, then this box is full of methods with the same type of parameters. We compare MyDelegate pack with string name. name is a variable of string type, and pack can be said to be a variable of MyDelegate type.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{   
    public delegate void MyDelegate(string str);    //委托的声明  
  
    class roomfriend  //定义室友这个类  
    {   
        public static void takepackage(string name)  //定义一个取快递的方法  
        {  
           Console.WriteLine("我叫 {0} 这是一个取快递方法",name);  
            
        }  
        public static void shopping(string name)   //定义一个买东西的方法  
        {  
            Console.WriteLine("我叫 {0}  这是一个买东西的方法",name);  
        }  
      
    }  
    class girlfriend  //定义一个girlfriend 类  
    {  
        public static void accept(string name,MyDelegate package) //定义一个accept方法 将委托作为参数传入     
          {  
        package(name);  
    }  
}  
class program  
{  
    static void Main(string[] args)  
    {  
        MyDelegate myd = new MyDelegate(roomfriend.takepackage); //实例化一个委托“我”携带一个方法(将方法当参数传入)  
        
        myd += roomfriend.shopping;    // += 合并运算顺序执行方法   
  
        girlfriend.accept("HC555", myd);  
    }  
}
Copy after login

The result is the same

C# Learning Diary 19----Reference Type of Delegate (Delegate) Type

Reflection:

In the example I gave above, "roommate" or "roommate's girlfriend" is regarded as a class. When I call the method, I use the type name. Method name, if I use an instantiated object , pass the object name. Method name reference method to pass in the delegate:

roomfriend myfriend = new roomfriend(); // Instantiate the roommate into an object

MyDelegate myd = new MyDelegate(myfriend.tackpackage ; It turns out that although I declared takepackage as Public access in the code, it will still be compiled into a private field. This is related to the static we used when defining the method (more on this later). If it is removed, it can be This is done;

The above is the content of C# Learning Diary 19----Reference Type Delegate (Delegate) type. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template