C#入门经典 第六章 委托

C#入门经典

第六章 6.6

委托的声明非常类似于函数,但不带函数体,且要使用delegate关键字。

委托的声明指定了一个返回类型和一个参数列表。

在定义了委托后,就可以声明该委托类型的变量。

接着把这个变量初始化为与委托有相同返回类型和参数列表的函数引用。

之后,就可以使用委托变量调用这个函数,就像该变量是一个函数一样。

 

有了引用函数的变量后,还可以执行不能用其它方式完成的操作。

例如,可以把委托变量作为参数传递给一个函数,这样,该函数就可以使用委托调用引用它的任何函数。

而且在运行之前无需知道调用的是那一个函数。

class Ch06Ex05
    {
        //委托的声明非常类似于函数,但不带函数体,且要使用delegate关键字。
        //委托的声明指定了一个返回类型和一个参数列表。
        delegate double ProcessDelegate(double a,double b);//返回类型是double,参数列表:两个double变量a和b
        static double Multiply(double x,double y)
        {
            return x * y;
        }

        static double Divide(double m, double n)
        {
            return m / n;
        }

        public static void Method()
        {
            ProcessDelegate process;//在定义了委托后,就可以声明该委托类型的变量。
            process = new ProcessDelegate(Multiply);//把委托变量初始化为与委托有相同返回类型和参数列表的函数引用。
            Console.WriteLine("Multiply(100,10)={0}", process(100, 10));//使用委托变量调用这个函数,就像该变量是一个函数一样
            process = new ProcessDelegate(Divide);//把委托变量初始化为与委托有相同返回类型和参数列表的函数引用。
            process(100, 10);//使用委托变量调用这个函数,就像该变量是一个函数一样
            Console.WriteLine("Divide(100,10)={0}", process(100, 10));
        }
    }

 class Program
    {
        /// <summary>
        /// 主函数
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            Chapter06.Ch06Ex05.Method();
            Console.Read();
        }
    }

delegate关键字指定该定义是用于委托的,而不是用于函数的(该定义所在的位置与函数定义相同)

 

 

 委托的三种用法

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

 ps:还有一种用法是,直接把方法名赋值给委托,不需要new

posted @ 2014-10-21 20:22  ChuckLu  阅读(408)  评论(0编辑  收藏  举报