The representative element is the more complex concept in C #, and the function pointers in C # are very similar to those of C + + using a representative element to encapsulate a reference representing the inner method of the element and then use the method that represents the meta reference through it.
It has a feature that does not need to know that the referenced method belongs to that class object as long as the number of arguments and return type of the function is the same as the Representative object. This may be more abstract I would like to give a few simple examples to the general beginners some basic understanding.
//定义一个返回值为string的无参数的代表元
注意这个代表元只能引用对象中
返回值为string的无参数方法
delegate string MyDelegate();
public class MyClass
{
public string SayHello()
{
return "Hello the world!";
}
}
public class TestMyClass
{
public static void Main(string[] args)
{
MyClass myClass1=new MyClass();
MyDelegate myDelegate1=new MyDelegate(myClass1.SayHello);
//下面就使用myDelegate1代替对象myClass1的SayHello方法
System.Console.WriteLine(myDelegate1());
//输出结果为hello the world!
与调用myClass1.SayHello();效果相同
}
}
If the representative is only this function, it will not be of much use, one of the most useful features of the representation element is the definition of a composite representing a meta object, with only the same type of representative Guancai able to compound + can define a composite representing a meta object-removing a representative element from a composite representative element:
delegate void MyDelegate(string s);
public class MyClass
{
public void SayHello(string who)
{
System.Console.WriteLine( who+"hello!");
}
public void SayGoodBye(string who)
{
System.Console.WriteLine( who+"good bye!");
}
}
public class TestMyClass
{
public static void Main(string[] args)
{
MyClass myClass1=new MyClass();
MyDelegate myDelegate,myDelegate1;
myDelegate=new MyDelegate(myClass1.SayHello);
myDelegate1=new MyDelegate(myClass1.SayGoodBye);
myDelegate+=myDelegate1;
//这样调用myDeletage就相当于同时调用了
myClass1.SayHello和myClass1.SayGoodBye
myDelegate("love.net ");
//执行结果输出love.net hello! love.net good bye!
}
}