Delegate的用法

一  调用多个方法

 

delegate   void  SampleDelegate( string  content);
   
    
class  Program
    
{
        
static void Main(string[] args)
        
{
            SampleDelegate d1, d2, d3, d4, d5;
            d1 
= SayHello2;
            d2 
= SayHi2;
            d3 
= d1 + d2;
            d4 
= d3 - d1;
            d5 
= d1 + d1;
            Console.WriteLine(
"Invoking delegate d1:");
            d1(
"Daniel");
            Console.WriteLine();
            Console.WriteLine(
"Invoking delegate d2:");
            d2(
"Daniel");
            Console.WriteLine();
            Console.WriteLine(
"Invoking delegate d3:");
            d3(
"Daniel");
            Console.WriteLine();
            Console.WriteLine(
"Invoking delegate d4:");
            d4(
"Daniel");
            Console.WriteLine();
            Console.WriteLine(
"Invoking delegate d5:");
            d5(
"Daniel");
            Console.WriteLine();

            Console.ReadLine();
        }

        
static void SayHello(string name)
        
{
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(
"Hello, {0}", name);
        }

        
static void SayHi(string name)
        
{
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine(
"Hi, {0}", name);
        }

        
static void SayHello2(string name)
        
{
            Thread.Sleep(
1000);
            Console.WriteLine(
"Hello, {0}", name);
        }

        
static void SayHi2(string name)
        
{
            Thread.Sleep(
1000);
            Console.WriteLine(
"Hi, {0}", name);
        }

    }

二 定义事件

 

  class  Program
    
{
        
static void Main(string[] args)
        
{
            Program prog 
= new Program();
            SayHelloHandler handler 
= new SayHelloHandler(SayHello);
            
// 同步调用
            Console.WriteLine("synchronous invoke begin");
            Console.WriteLine(handler.Invoke(
"Daniel"));
            Console.WriteLine(
"synchronous invoke end");
            Console.WriteLine();
            
// 异步调用
            Console.WriteLine("asynchronous invoke begin");
            handler.BeginInvoke(
"Daniel"new AsyncCallback(callback), handler);
            Console.WriteLine(
"asynchronous invoke end");
            Console.ReadLine();
        }

        
public static string SayHello(string name)
        
{
            Thread.Sleep(
10000);
            
return string.Format("Hello World, {0}!", name);
        }

        
public static void callback(IAsyncResult ar)
        
{
            SayHelloHandler handler 
= (SayHelloHandler)ar.AsyncState;
            Console.WriteLine(handler.EndInvoke(ar));
        }

    }

    
delegate   string  SayHelloHandler( string  name);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值