//委托例子
/*委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,
这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,
同时使得程序具有更好的可扩展性。
*/
//之一
using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
//之二
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
//定义委托,它定义了可以代表的方法的类型
public delegate void GreetingDelegate(string name);
class Program
{
private static void EnglishGreeting(string name)
{
Console.WriteLine("Morning, " + name);
}
private static void ChineseGreeting(string name)
{
Console.WriteLine("早上好, " + name);
}
//注意此方法,它接受一个GreetingDelegate类型的方法作为参数
private static void GreetPeople(string name, GreetingDelegate MakeGreeting)
{
MakeGreeting(name);
}
static void Main(string[] args)
{
GreetPeople("Jimmy Zhang", EnglishGreeting);
GreetPeople("张子阳", ChineseGreeting);
Console.ReadKey();
}
}
}
//委托写在两个类
//1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate
{
class GreetingManager
{
public event GreetingDelegate delegate1;
public void GreetPeople(string name, GreetingDelegate MakeGreeting)
{
MakeGreeting(name);
}
}
}
//2
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
//定义委托,它定义了可以代表的方法的类型
public delegate void GreetingDelegate(string name);
class Program
{
private static void EnglishGreeting(string name)
{
Console.WriteLine("Morning, " + name);
}
private static void ChineseGreeting(string name)
{
Console.WriteLine("早上好, " + name);
}
static void Main(string[] args)
{
GreetingManager gm = new GreetingManager();
GreetingDelegate delegate1;
delegate1 = EnglishGreeting;
delegate1 += ChineseGreeting;
gm.GreetPeople("Jimmy Zhang", delegate1);
Console.ReadKey();
}
}
}
//结束
委托例子
最新推荐文章于 2023-07-22 15:08:11 发布