In the eyes of C and C + + programmers, pointers are one of their most powerful tools, and they bring a lot of distress to them. Because the data type that the pointer points to may not be the same, for example, you can point a pointer of type int to a variable of type float, and then the program doesn't go wrong. Also, if you delete a pointer that should not be deleted (such as a pointer to the main program in Windows), the program can crash. This shows that the misuse of pointers to the security of the program buried hidden dangers.
Because of this, the concept of pointers is eliminated in the C # language. Of course, programmers who are reluctant to the pointer can still use pointers in C #, but must declare that the program is "unsafe". And what we're going to be talking about here is a reference type for C #--Representative (delegate). It actually corresponds to a function pointer prototype in C #. Unlike pointers, the representative is type-safe in C #.
When declaring a representation, you only need to specify the type that represents the prototype to which it is pointing, and it cannot have a return value or an argument with an output type. For example, we can declare a representative that points to an int type function prototype:
delegate int mydelegate ();
If we declare a representative of our own, then it is an extension of the system-defined class System.Delegate. In the representative instance, we can encapsulate a static method, or we can encapsulate a non-static method. Let's look at the following example:
Program Listing 4-2:
Using System;
delegate int mydelegate (); Declares a representative of the public
class MyClass
{public
int instancemethod () {
console. WriteLine ("Call the instance method.");
return 0;
}
static public int Staticmethod () {
Console.WriteLine (called the Static method.);
return 0;
}
}
public class Test
{
static public void Main ()
{
MyClass p=new MyClass ();
The representative points to the Non-static method Instancemethod
mydelegate d=new mydelegate (p.instancemethod);
Calls Non-static method
D ();
Will represent the static method Staticmethod
d=new mydelegate (myclass.staticmethod);
Call static method
D ();
}
}
The result of the program's output is: Call the
instance method.
Call the static method.