委托(C#)
委托,delegate 关键字用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。委托类型声明的格式如下:
public delegate void TestDelegate(string message);
首先,我们看一下MSDN上定义的例子:
复制代码
using System;
class MainClass
{
// Regular method that matches signature:定义委托 - 定义所需的签名:
delegate void SampleDelegate(string message);
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
d1("Hello");
// Invoke delegate d2:调用委托d2
d2("World");
Console.ReadLine();
}
}
复制代码
在上述例子中,SampleDelegate为我们定义的委托,可以把委托看做一个类去对待,其签名必须与所调用的函数的参数类型一致。实例化委托d1,并将其指向命名方法SampleDelegateMethod。调用委托d1,并为其传递“Hello”作为参数,实质相当于直接调用d1所指向的方法SampleDelegateMethod("Hello");实例化委托d2,并将其指向含有string类型参数message的匿名方法。调用委托d2,相当于直接调用匿名方法。
eg1:假设老板给了A、B、C各1000元,让他们分别换大米、小麦和棉花,如果用委托,应该怎么去实现呢?
复制代码
namespace ConsoleApplication3
{
public delegate string ReturnDelegate();
class Program
{
static void Main(string[] args)
{
ReturnDelegate pa = new ReturnDelegate(A.Return);
Console.WriteLine(pa());
ReturnDelegate pb = new ReturnDelegate(B.Return);
Console.WriteLine(pb());
ReturnDelegate pc = new ReturnDelegate(C.Return);
Console.WriteLine(pc());
Console.ReadLine();
}
}
class A
{
public static string Return()
{
return "A换得了100斤大米!";
}
}
class B
{
public static string Return()
{
return "B换得了100斤小麦!";
}
}
class C
{
public static string Return()
{
return "C换得了100斤棉花!";
}
}
}
复制代码
同样,也可以采用Invoke()方法去调用委托实现同样的效果,代码如下:
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplicatio2
{
public delegate void ReturnDelegate();
class Program
{
static void Main(string[] args)
{
King p = new King();
ReturnDelegate Aew = new ReturnDelegate(A.ReturnResult);
Aew.Invoke();
ReturnDelegate Brw = new ReturnDelegate(B.ReturnResult);
Brw.Invoke();
ReturnDelegate Crw = new ReturnDelegate(C.ReturnResult);
Crw.Invoke();
Console.ReadLine();
}
}
class King
{
private string Command = "给你们三个人各1000元,你们去给我换玉米、小麦、棉花";
public King()
{
Console.WriteLine(Command);
}
}
class Person
{
}
class A:Person
{
public static void ReturnResult()
{
Console.WriteLine("A换得了10袋玉米");
}
}
class B:Person
{
public static void ReturnResult()
{
Console.WriteLine("B换得了100斤小麦");
}
}
class C:Person
{
public static void ReturnResult()
{
Console.WriteLine("C换得了100斤棉花");
}
}
}
复制代码
eg2:接下来,我们看看委托的由来、使用委托有什么好处。
我们在屏幕前输入一句问候语:
public void GreetPeople(string name)
{
EnglishGreeting(name);
}
public void EnglishGreeting(string name)
{
Console.WriteLine("Morning, " + name);
}
企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:上海网络公司 http://www.flpsz.com