using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegateTest
{
public delegate void SayDelegate(string name);
class Program
{
static void Main(string[] args)
{
DelegateClass dc = new DelegateClass();
SayDelegate sayDelegate1 = new SayDelegate(dc.ChineseSay);//使用new来实例化委托对象,并将方法作为参数传递给委托
SayDelegate sayDelegate2 = dc.EnglishSay;//直接将方法指定给委托对象
dc.Say("周义康", sayDelegate1);//使用say方法来使用委托
dc.Say("Brian", sayDelegate2);
SayDelegate sayDelegate3 = delegate (string name)//使用匿名方法来为委托指定方法
{
Console.WriteLine(name);
Console.WriteLine(" 阿尼嘎多");
};//注意有分号
sayDelegate3("satosi gogo");
Console.ReadLine();
}
}
public class DelegateClass
{
public void ChineseSay(string name)
{
Console.WriteLine("你好,{0}!", name);
Console.WriteLine();
}
public void EnglishSay(string name)
{
Console.WriteLine("Hello,{0}!", name);
Console.WriteLine();
}
public void Say(string name,SayDelegate sayDelegate)
{
sayDelegate(name);
}
}
}
委托实现的三种方法
最新推荐文章于 2022-04-28 15:09:18 发布