我一直忙于潜入lambda表达式最近,还有就是我一直想学习,但也只是似乎没有做头或尾巴一些特定的功能。
假设我有以下逻辑在我的代码:
列表< A>富; //假设这是填充的String []巴= foo.Select< A,串>(X => x.StringProperty).ToArray<串GT;();现在,我想也许是抽象的整体运作成为一个处理方法,这样我可以做到这一点,而不是
的String []栏= MakeArray< A,串>(foo,那么X => x.StringProperty); INT [] = foobar的&MakeArray LT; A,INT>(foo,那么X => x.IntegerProperty);
我怎么会去与编写方法的身材?我预见宣布签名是这样的:
U [] MakeArray< T,U>(/ *一些拉姆达魔法* /)其中T:IEntity {}但我不知道如何指定我期待一个lambda表达式作为方法的参数,以及如何转换正好进入方法的主体。
有人能告诉我如何创建上述MakeArray()功能?我敢肯定,一旦我看到它是如何做,我可以从那里把它捡起来。
修改
由于在评论中指出, MakeArray()需要一个参考的IEnumerable<> 。已更新,以反映
解决方案 公共静态U [] MakeArray< T,U> (这IEnumerable的< T> @enum,Func键< T,U>规则) {返回@ enum.Select(规则).ToArray(); }
I've been busy diving into lambda expressions recently, and there's some specific functionality that I've been meaning to learn but just couldn't seem to make heads or tails of.
Suppose that I have the following logic in my code:
List<A> foo; // assuming this is populated string[] bar = foo.Select<A,string>(x => x.StringProperty).ToArray<string>();Now, I want to perhaps abstract that whole operation into a handler method so that I can do this instead:
string[] bar = MakeArray<A,string>(foo, x => x.StringProperty); int[] foobar = MakeArray<A,int>(foo, x => x.IntegerProperty);How would I go about with writing that method's body? I foresee declaring the signature as something like:
U[] MakeArray<T,U>( /* some lambda magic? */ ) where T : IEntity {}but I don't know how to specify that I'm expecting a lambda expression as the method argument, and how that translates exactly into the body of the method.
Can anybody show me how to create the MakeArray() function above? I'm pretty sure that once I see how it's done, that I can pick it up from there.
EDIT
As pointed out in the comments, MakeArray() needed a reference to the IEnumerable<>. Updated to reflect that.
解决方案 public static U[] MakeArray<T, U>(this IEnumerable<T> @enum, Func<T, U> rule) { return @enum.Select(rule).ToArray(); }
更多推荐
C#lambda表达式作为函数的参数
发布评论