2012-01-18 64 views
1

我有以下方法:如何使用/理解lambda表達式?

private byte[] GetEmailAsBytes(string lstrBody) 
{ 
    byte[] lbytBody; 
    ASCIIEncoding lASCIIEncoding = new ASCIIEncoding(); 
    lbytBody = lASCIIEncoding.GetBytes(lstrBody); 
    return lbytBody; 
} 

我想知道,這可以轉換爲一個lambda表達式。我新來這個。我曾嘗試過:

Func<string> BodyToBytes = x => { 
     ASCIIEncoding lASCIIEncoding = new ASCIIEncoding(); 
     return lASCIIEncoding.GetBytes(x); 
} 

但這不能編譯。簡單地說,我希望將字符串轉換爲一系列字節,並且爲了感興趣,我們希望使用lambda表達式來執行此操作。

回答

6

表達式Func<string>相當於一個不接受參數並返回string的函數。

你的例子清楚地返回byte[],但你它接受string並返回一個byte[]

要解決此問題,請將BodyToBytes更改爲匹配以下內容。請注意,參數的類型首先以逗號分隔,然後是返回類型。在這種情況下,x將是string類型。

Func<string, byte[]> BodyToBytes = x => { 
     ASCIIEncoding lASCIIEncoding = new ASCIIEncoding(); 
     return lASCIIEncoding.GetBytes(x); 
} 

對於參考,見Func TypeMSDN docs

1

我寫了一個NUnit的例子,我個人的理解。

private class ld 
    { 
     public Boolean make<T>(T param, Func<T, bool> func) 
     { 
      return func(param); 
     } 
    } 

    private class box 
    { 
     public Boolean GetTrue() { return true; } 
     public int Secret = 5; 
    } 

    [Test] 
    public void shouldDemonstrateLambdaExpressions() 
    { 
     //Normal Boolean Statement with integer 
     int a = 5; 
     Assert.IsTrue(a == 5); 
     Assert.IsFalse(a == 4); 

     //Boolean Statement Expressed Via Simple Lambda Expression 
     Func<int, bool> myFunc = x => x == 5; 
     Assert.IsTrue(myFunc(5)); 
     Assert.IsFalse(myFunc(4)); 

     //Encapsuled Lambda Expression Called on Integer By Generic Class with integer 
     ld t = new ld(); 
     Assert.IsTrue(t.make<int>(5,myFunc)); 
     Assert.IsFalse(t.make<int>(4, myFunc)); 

     //Encapsuled Lambda Expression Called on Integer By Generic Class with implicit Generics 
     Assert.IsTrue(t.make(5, myFunc)); 

     //Simple Lambda Expression Called on Integer By Generic Class with implicit Generic 
     Assert.IsTrue(t.make(20, (x => x == 20))); 
     Assert.IsTrue(t.make(20, (x => x > 12))); 
     Assert.IsTrue(t.make(20, (x => x < 100))); 
     Assert.IsTrue(t.make(20, (x => true))); 

     //Simple Lambda Expression Called on a Class By Generic Class with implicit Generic 
     //FULL LAMBDA POWER REACHED 
     box b = new box(); 
     Assert.IsTrue(t.make(b, (x => x.GetTrue()))); 
     Assert.IsTrue(t.make(b, (x => x.Secret == 5))); 
     Assert.IsFalse(t.make(b, (x => x.Secret == 4))); 
    }