给个例子看看:
代理:
(1)
using System;
public delegate void mfDelegate(string name);
public class MikeCat
{
public static void Hello(string name)
{
Console.WriteLine ("您好!"+name);
}
public static void GoodBye(string name)
{
Console.WriteLine ("再见"+name);
}
public static void Main()
{
mfDelegate mf1=new mfDelegate (Hello);
mf1("mikecat");
mfDelegate mf2=new mfDelegate (GoodBye);
mf2("mikdecat");
mfDelegate mf3=mf1+mf2;
mf3("迈克老猫");
mfDelegate mf4=mf3-mf1;
mf4("mikecat");
}
}
(2)
using System;
delegate int Mydelegate();
public class MyClass
{
public int InstanceMethod()
{
Console.WriteLine ("Call the instance method.");
return 0;
}
static public int StaticMethod()
{
Console.WriteLine ("Call the static method.");
return 0;
}
}
public class Test
{
static public void Main()
{
MyClass p=new MyClass ();
//将指针指向非静态的方法InstanceMethod
Mydelegate d=new Mydelegate (p.InstanceMethod );
//调用非静态方法
d();
//将代表指向静态的方法StaticMethod;
d=new Mydelegate (MyClass.StaticMethod );
//调用静态方法
d();
}
}
委托:
using System;
namespace _05_06
{
public delegate string MyDelegate(string drg);
public class Class_05_06
{
public static string DoNothing(string s)
{
return s;
}
public string ToLower(string s)
{
return s.ToLower ();
}
public static string ToUpper(string s)
{
return s.ToUpper ();
}
public static void Main()
{
MyDelegate d1,d2,d3;
Class_05_06 c=new Class_05_06 ();
d1=new MyDelegate (Class_05_06.DoNothing );
d2=new MyDelegate (c.ToLower );
d3=new MyDelegate (Class_05_06.ToUpper );
string s="This is a string";
Console.WriteLine (d1(s));
Console.WriteLine (d2(s));
Console.WriteLine (d3(s));
}
}
}