给你个简单的两个数相加的例子: using System; namespace Add { delegate void numberAdd(int a, int b); //声明委托 class program { static void Main() { numberAdd n1 = delegate(int a, int b) //实例化委托对象,委托是引用类型。 { Console.WriteLine(a + b); }; int x = int.Parse(Console.ReadLine()); int y = int.Parse(Console.ReadLine()); n1(x, y); Console.ReadLine(); } } }
// keyword_delegate2.cs
// Calling both static and instance methods from delegatesusing System;
// delegate declarationdelegatevoid MyDelegate();
publicclass MyClass
{
publicvoid InstanceMethod()
{
Console.WriteLine("A message from the instance method.");
}
staticpublicvoid StaticMethod()
{
Console.WriteLine("A message from the static method.");
}
}
publicclass MainClass
{
staticpublicvoid Main()
{
MyClass p =new MyClass();
// Map the delegate to the instance method: MyDelegate d =new MyDelegate(p.InstanceMethod);
d();
// Map to the static method: d =new MyDelegate(MyClass.StaticMethod);
d();
}
}