zoukankan      html  css  js  c++  java
  • C#的匿名方法

    匿名方法是在初始化委托时内联声明的方法。

    例如下面这两个例子:

    不使用匿名方法的委托:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication7
    {
        class Program
        {
            public static int add(int x)
            {
                return x + 20;
            }
            delegate int otherdel(int param);
            public static void Main()
            {
                otherdel del = add;
    
                Console.WriteLine("{0}", del(20));
                Console.WriteLine("{0}", del(10));
            }
        } 
    }

    使用匿名方法的委托:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication7
    {
        class Program
        {
            delegate int otherdel(int param);
            public static void Main()
            {
                otherdel del = delegate(int x)
                {
                    return x + 20;
                };
    
                Console.WriteLine("{0}", del(20));
                Console.WriteLine("{0}", del(10));
            }
        } 
    }

    两种结果是一样的。

    使用匿名方法

    1)声明委托变量时候作为初始化表达式。

    2)组合委托时在赋值语句的右边。

    3)为委托增加事件时在赋值语句的右边。

    匿名方法语法

    delegate (parameters ){implementationcode};

    关键字  参数        语句块

    匿名方法不会声明返回值类型。但是匿名方法返回值类型必须和委托返回值一样。

    参数:参数数量,类型和修饰符必须和委托一样。

    但是我们可以使圆括号为空,或省略圆括号来简化匿名方法的参数列表。但是仅在下面两项都为真的情况下才可以这么做。

    1,委托的参数列表不包含任何out参数的委托。

    2,匿名方法不使用任何参数。

    例如下面:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication7
    {
        class Program
        {
            delegate int otherdel(int param);
            public static void Main()
            {
                otherdel del = delegate
                {
                    cleanup();
                    printMessage();
                };          
            }
        } 
    }

     params参数:

    如果委托参数包含params参数,那么params关键字就会被匿名方法的参数列表忽略。如下:

    delegate int otherdel(int x,params int y);
            otherdel del = delegate(int x,int y)
            {
                -------------
            };
  • 相关阅读:
    Linux各个目录的作用及内容
    发现未授权登录用户怎么办
    开启GodMode
    通过域名方式决定使用哪个数据库的方式分享
    openerp-server.conf 中配置 dbfilter 参数无效的解决办法
    OpenERP7.0 忘记admin管理员密码解决办法
    DEB方式在UBUNTU安装ODOO 8.0
    解决apt-get的E: Could not get lock /var/lib/dpkg/lock方法
    Ubuntu 11.04 (Natty) 已经停止支持 但可以使用old-releases源了
    How to get the url of a page in OpenERP?
  • 原文地址:https://www.cnblogs.com/alsf/p/5996563.html
Copyright © 2011-2022 走看看