如何使用/理解lambda表达式?

时间:2012-01-18 02:10:41

标签: c# 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表达式。

2 个答案:

答案 0 :(得分: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 :(得分: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)));
    }