C#lambda表达式作为函数的参数

编程入门 行业动态 更新时间:2024-10-19 11:45:14
本文介绍了C#lambda表达式作为函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直忙于潜入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表达式作为函数的参数

本文发布于:2023-11-08 07:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568741.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   函数   参数   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!