LINQ 中Select方法将Func委托作为参数传入出错原因不明。望指教

Slogic 2016-03-01 04:13:31
问题:
IEnumerable<String> aWords = words.Select(selector);
以上语句编译出错。是否可以使用Funs委托作为Linq方法Select的参数,如果可以该如何做。

源代码:
1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Linq;
5
6 static class Func
7 {
8 static void Main(string[] args)
9 {
10 // 声明了一个Func委托类型的变量selector并用Lambda表达式进行实例化
11 // 这个Lambda表达式将用来获取一个字符串并将这个字符串转化为大写并返回
12 Func<string, string> selector = str => str.ToUpper();
13
14 // 创建一个字符串数组
15 string[] words = { "orange", "apple", "Article", "elephant" };
16 // 依次遍历这个字符串数组并调用委托实例selector进行处理
17 IEnumerable<String> aWords = words.Select(selector);
18
19 // 输出结果到控制台
20 foreach (String word in aWords)
21 Console.WriteLine(word);
22 }
23 }
24 /*
25 This code example produces the following output:
26
27 ORANGE
28 APPLE
29 ARTICLE
30 ELEPHANT
31 */

...全文
225 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Slogic 2016-03-01
  • 打赏
  • 举报
回复
引用 5 楼 xuzuning 的回复:
        static void Main(string[] args)
        {
            Func<string, string> selector = str => str.ToUpper();
            string[] words = { "orange", "apple", "Article", "elephant" };
            IEnumerable<String> aWords = words.Select(selector);
            foreach (String word in aWords) Console.WriteLine(word);
        }
没有任何问题!
是的,谢谢大家,是我的代码有问题。在类外面有定义 public delegate TResult Func<TArg0, TResult>(TArg0 arg0);这多余代码导致问题发生。
xuzuning 2016-03-01
  • 打赏
  • 举报
回复
        static void Main(string[] args)
{
Func<string, string> selector = str => str.ToUpper();
string[] words = { "orange", "apple", "Article", "elephant" };
IEnumerable<String> aWords = words.Select(selector);
foreach (String word in aWords) Console.WriteLine(word);
}

没有任何问题!
Slogic 2016-03-01
  • 打赏
  • 举报
回复
引用 2 楼 duanzi_peng 的回复:
func第一个参数是输入的值,第二个是返回的值。用1#的方式。
是的,#1提供的方法能理解只是 https://msdn.microsoft.com/zh-cn/library/bb549151(v=vs.90).aspx 中最后的代码。调用Func的方式是错误的?
Slogic 2016-03-01
  • 打赏
  • 举报
回复
引用 1 楼 starfd 的回复:
改成 Select(s=>selector(s)) 试试
按照大大所说可以,我提供的代码是msdn提供的代码,会出现编译错误。总有些疑惑。
exception92 2016-03-01
  • 打赏
  • 举报
回复
func第一个参数是输入的值,第二个是返回的值。用1#的方式。
  • 打赏
  • 举报
回复
改成 Select(s=>selector(s)) 试试

110,523

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧