C# 委托

/**/ /*
 * 由 SharpDevelop 创建。
 * 用户: huy
 * 日期: 2010-3-6
 * 时间: 23:30
*/


using  System;
using  System.Threading;
delegate   void  EatDelegate( string  food);
class  MyDelegate
{
    
static void zsEat(string food)
    
{
        Console.WriteLine(
"张三"+food);
    }

    
    
static void Main()
    
{
        EatDelegate zs 
= new EatDelegate(zsEat);
        zs(
"西瓜");
        Thread.Sleep(
5000);
    }

}



当我们需要把方法做为参数传递给其他方法的时候,就需要使用委托。

因为有时候,我们要操作的对象,不是针对数据进行的,而是针对某个方法进行的操作。

       我们还是来以代码入手

 

Code
using System;
namespace gosoa.com.cn
{
    public class test
    {
        public delegate string GetAString();
        public static void Main()
        {
            int x=10;
            GetAString firstString=new GetAString(x.ToString);
            Console.WriteLine(firstString());
            //上句和下面这句类似。
            //Console.WriteLine(x.ToString());
        }
    }
}

在上例中,public delegate string GetAString(); 就是声明了一个委托(delegate),其语法和方法的定义类似,只是没有方法体,前面要加上关键字 delegate 。定义一个委托,基本上是定义一个新类,所以,可以在任何定义类的地方,定义委托。

注意,在C#中,委托总是自带一个有参数的构造函数,这就是为什么在上例中,GetAString firstString=new GetAString(x.ToString); 通过这句初始化一个新的delegate的时候,给传递了一个x.ToString 方法。但,在定义delegate的时候,却没有定义参数。

      

在看另一个例子之前,我们先来了解下匿名方法。

       匿名方法的使用,我们看个例子

Code
using System;
namespace gosoa.com.cn
{
    public class test
    {
        delegate string GetUrl(string val);
        static void Main(string [] args)
        {
            string domin="asaadsad";
            GetUrl url=delegate(string  param)
            {
                 param="http://"+param;
                 return param;
            };
            Console.WriteLine(url(domin));
        }
    }
}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sendling/archive/2009/03/02/3948561.aspx

你可能感兴趣的:(thread,C++,c,.net,C#)