简体   繁体   English

带有Lambda的C#技巧

[英]C# Trick with lambdas

There is some code, but the thing is very simple. 有一些代码,但是事情很简单。 I want to pass a function as a parameter, but the function is so short that it could've been created by lambda. 我想将一个函数作为参数传递,但是该函数是如此之短,以至于它可能是由lambda创建的。

    class Hidden
    {
        public List<string> GetData()
        {
            return new List<string>();
        }
    }

    class Main
    {
        Dictionary<int, Hidden> dir = new Dictionary<int, Hidden>();

        public Main()
        {
            Friend f = new Friend(MethodToBeReplacedByLambda);
        }

        public List<string> MethodToBeReplacedByLambda(int id)
        {
            return dir[id].GetData();
        }
    }

    class Friend
    {
        public Friend(Func<int, List<string>> GetData)
        {
            List<string> result = GetData(4);
        }
    }

I want to delete this method 我想删除此方法

    public List<string> MethodToBeReplacedByLambda(int id)
    {
        return dir[id].GetData();
    }

And be able to pass this as a parameter by lambda. 并能够通过lambda将此作为参数传递。 Any ideas? 有任何想法吗? :D :d

UPDATE: I've tried: 更新:我试过了:

Friend f = new Friend((int, List<string>) => dir[id].GetData());
Friend f = new Friend((id) => dir[id].GetData());

Simply create a lambda that uses the int value from the function: 只需创建一个使用函数中的int值的lambda即可:

Friend f = new Friend(id => dir[id].GetData())

Only the parameter names (that you use) need to be passed to the lambda, and not the return value of GetData . 仅需要将(您使用的)参数名称传递给lambda,而不是GetData的返回值。 If you have multiple parameters, wrap them in parenthesis. 如果您有多个参数,请将其括在括号中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM