C#匿名方法和lambda

来源:互联网 发布:什么是数据生态圈 编辑:程序博客网 时间:2024/05/22 10:31

1.当一个调用者想监听传进来的事件,他必须定义一个唯一的与相关联委托签名匹配的方法,而该方法基本不会被调用委托之外的任何程序所调用。这里可以在事件注册时直接讲一个委托与一段代码相关联,这种代码成为匿名方法。

示例:

public class MyClass9
    { 
        public EventHandler TestEventHandler ;
        public void Func1()
        {
            TestEventHandler += delegate(object sender, EventArgs e)
            {
                Console.WriteLine("匿名方法");
            };
            TestEventHandler(this, new EventArgs());
        }
    }

2.匿名方法注意事项

匿名方法不能访问定义方法中的ref或out参数

匿名方法中的本地变量不能与外部方法中的本地变量重名

匿名方法可以访问外部类作用域中的实例变量(或静态变量)

匿名方法内的本地变量可以与外部类的成员变量同名(本地变量隐藏外部类的成员变量)


3.C#支持内联处理事件,通过直接把一段代码语句赋值给事件(使用匿名方法),而不是构建底层委托调用的独立方法。Lambda表达式只是用更简单的方式来写匿名方法,彻底简化了对.net委托类型的使用。

4.使用匿名方法示例:

List<T> 的FindAll()方法:

public List<T> FindAll(Predicate<T> match); //该方法的唯一参数为System.Predicate<T>类型的泛型委托。

public delegate bool Predicate<T> (T obj);  //该委托指向任意类型参数作为唯一输入参数并返回bool的方法。

使用普通:

public class MyClass10
    {
        private void Func1()
        {
            List<int> listInt = new List<int> { 1, 2, 3, 4, 5, 6 };
            Predicate<int> callback = new Predicate<int>(CallBackFunc);
            listInt.FindAll(callback);

        }
        private bool CallBackFunc(int obj)
        {
            if (obj > 3)
            {
                return true;
            }
            return false;
        }
    }

使用匿名方法:

public class MyClass10
    {
        private void Func1()
        {
            List<int> listInt = new List<int> { 1, 2, 3, 4, 5, 6 };          
            listInt.FindAll(
                delegate(int i)
                {
                    if (i > 3)
                        return true;
                    return false;
                });

        }        
    }

使用Lambda:

 public class MyClass10
    {
        private void Func1()
        {
            List<int> listInt = new List<int> { 1, 2, 3, 4, 5, 6 };
            listInt.FindAll(s => s > 3).ToList();  //这里编译器可以根据整个Lambda表达式的上下文和底层委托推断出s是一个整形
        }     
    }


5.多语句Lambda语句块(使用大括号括起来)

listInt.FindAll(s =>
            {
                Console.WriteLine("aaaaaaa");
                if (s > 3)
                    return true;
                if (s <= 3)
                    return false;
                return true;
            }
            );

6.使用Lambda重写MyClass9

public class MyClass9
    { 
        public EventHandler TestEventHandler ;
        public void Func1()
        {
            TestEventHandler += (sender, e) =>
            {
                Console.WriteLine("Just Test");
            };

        }
    }

0 0
原创粉丝点击