一步步理解Lambda表达式

1.泛型方法的简化

       public static void WL<T>(T input)
        
{
            Console.WriteLine(input);
        }

  调用:

      int a = 100;
           WL
<int>(a);
        WL(a);
     
//C#的编辑器会通过调用WL的方法获取参数类型,所以不要把泛型类型赋予方法

2.泛型委托:
先定义个泛型委托Del 

 public delegate void Del<T>(T item);
        
public static void WL<T>(T input)
        
{
            Console.WriteLine(input);
        }

   
int a = 100;
            
int b = 200;
            
int c = 300;
          
//  Del<int> m1 = new Del<int>(WL<int>); //效果同下行 ,可不必传给方法类型(见1)
            Del<int> m1 = new Del<int>(WL);
   
//匿名委托
            Del<int> m2 = delegate(int input)
            
{
                Console.WriteLine(input);
            }
;
            
//再进一步,C#2.0方法组转换的新功能,适用于具体委托类型和泛型委托类型
            Del<int> m3 = WL;
            m1(a);
            m2(b);
            m3(c);

 3.Lambda表达式和扩展方法
 如下:

          IList<int> list = new List<int>();
            list.Add(
4);
            list.Add(
5);
            list.Add(
6);
            var mylist 
= list.Where(i=> i > 5);
            
foreach (var item in mylist)
            
{
                Console.WriteLine(item);  
            }

   前提,如果你知道  i=>i>5 其实表示一个委托,
   类似这样的委托

            delegate(int input)
            
{
                
return input>5;
            }
;

然后记住这种玩意就是个委托,那么继续:  
  构造一个扩展方法:(Del是前面定义的泛型委托,扩展方法的语法假定你也知道)

   public static void Ext<T>(this T source, Del<T> D)
        
{
            D(source);
        }

  
//a.Ext<int>(m1); //原因如1中所述
  a.Ext(m1);//就是个委托
        a.Ext(i => Console.WriteLine(i)); //试试这个.然后再尝试理解LINQ命名空间里的其他方法

测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    
//扩展方法必须定义在静态的类中
    public static class Program
    
{
        
public delegate void Del<T>(T item);
        
public static void WL<T>(T input)
        
{
            Console.WriteLine(input);
        }

        
public static void Ext<T>(this T source, Del<T> D)
        
{
            D(source);
        }

        
static void Main(string[] args)
        
{
            
int a = 100;
            
int b = 200;
            
int c = 300;
          
//  Del<int> m1 = new Del<int>(WL<int>); //效果同下行 
            Del<int> m1 = new Del<int>(WL);
            Del
<int> m3 = delegate(int input)
            
{
                Console.WriteLine(input);
            }
;
            
//C#2.0方法组转换的新功能,适用于具体委托类型和泛型委托类型
            Del<int> m2 = WL;
            m1(a);
            m2(b);
            m3(c);
            
//a.Ext<int>(m1);
            a.Ext(m1);
            a.Ext(i 
=> Console.WriteLine(i));
           
        }

    }

}

以上是个人理解
  

posted on 2008-04-24 11:35  Haozes  阅读(1047)  评论(3编辑  收藏  举报