delegate void StringProcessor(string input);
class Person
{
string name;
public Person(string name)
{
this.name = name;
}
public void Say(string message)
{
Console.WriteLine("{0} says: {1}", name, message);
}
}
class Background
{
public static void Note(string note)
{
Console.WriteLine("({0})", note);
}
}
[Description("Listing 2.1")]
class SimpleDelegateUse
{
static void Main()
{
Person jon = new Person("Jon");
Person tom = new Person("Tom");
StringProcessor jonsVoice, tomsVoice, background;
jonsVoice = new StringProcessor(jon.Say);
tomsVoice = new StringProcessor(tom.Say);
background = new StringProcessor(Background.Note);
jonsVoice("Hello, son.");
tomsVoice.Invoke("Hello, Daddy!");
background("An airplane flies past.");
}
} delegate void StringProcessor(string input);声明委托的类型
public void Say(string message)
{
Console.WriteLine("{0} says: {1}", name, message);
}声明兼容的实例方法
public static void Note(string note)
{
Console.WriteLine("({0})", note);
}兼容的静态方法
StringProcessor jonsVoice, tomsVoice, background;
jonsVoice = new StringProcessor(jon.Say);
tomsVoice = new StringProcessor(tom.Say);
background = new StringProcessor(Background.Note);
创建三个委托实例
jonsVoice("Hello, son.");
tomsVoice.Invoke("Hello, Daddy!");
background("An airplane flies past.");调用委托实例
先声明委托类型,接着创建两个方法,都与委托兼容。 一个实例方法 Person.Say 一个是静态方法 Background.Note
创建了,两个Person 类的实例
JonsVoice调用的 是name 为 jon的 那个Person对象的 Say 方法
tomsVoice调用的 是name 为 Tom的 对象的 Say方法
调用委托有两种, 显示调用invoke 或者 c#的简化
为什么要委托,委托就是把指令给别人,让别人来执行
如果你想单击某个按钮,发生某些事情,但又不想或者不能改变 按钮的代码,就可以用委托
委托其实是间接的完成事情
变得更灵活,而不是不断地改代码
输入
jonsVoice = new StringProcessor(jon.Say);
tomsVoice = new StringProcessor(tom.Say);
background = new StringProcessor(Background.Note); jonsVoice("Hello, son.");
tomsVoice.Invoke("Hello, Daddy!");
background("An airplane flies past.");结果
Jon says: Hello, son.
Tom says: Hello, Daddy!
(An airplane flies past.)
本文通过一个具体的C#代码示例介绍了如何定义和使用委托。包括声明委托类型、创建兼容的方法、实例化委托并调用它们的过程。展示了委托在不同场景下的灵活性。
3543

被折叠的 条评论
为什么被折叠?



