gpt4 book ai didi

c# - 动态、linq 和 Select()

转载 作者:可可西里 更新时间:2023-11-01 08:08:55 25 4
gpt4 key购买 nike

考虑以下(无意义,但用于说明目的)测试类:

public class Test
{
public IEnumerable<string> ToEnumerableStrsWontCompile(IEnumerable<dynamic> t)
{
return t.Select(x => ToStr(x));
}

public IEnumerable<string> ToEnumerableStrsWillCompile(IEnumerable<dynamic> t)
{
var res = new List<string>();

foreach (var d in t)
{
res.Add(ToStr(d));
}

return res;
}

public string ToStr(dynamic d)
{
return new string(d.GetType());
}
}

为什么在 t.Select(x => ToStr(x)) 上编译时出现以下错误?

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<dynamic>' 
to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion
exists (are you missing a cast?)

第二种方法没有报错。

最佳答案

我相信这里发生的是因为表达式 ToStr(x)涉及 dynamic变量,整个表达式的结果类型也是dynamic ;这就是为什么编译器认为它有一个 IEnumerable<dynamic>它期望 IEnumerable<string> 的地方.

public IEnumerable<string> ToEnumerableStrsWontCompile(IEnumerable<dynamic> t)
{
return t.Select(x => ToStr(x));
}

有两种方法可以解决这个问题。

使用显式转换:

public IEnumerable<string> ToEnumerableStrsWontCompile(IEnumerable<dynamic> t)
{
return t.Select(x => (string)ToStr(x));
}

这告诉编译器表达式的结果肯定是一个字符串,所以我们最终得到一个 IEnumerable<string>。 .

用方法组替换 lambda:

public IEnumerable<string> ToEnumerableStrsWontCompile(IEnumerable<dynamic> t)
{
return t.Select(ToStr);
}

这样编译器隐式地将方法组表达式转换为 lambda。请注意,由于没有提及 dynamic变量 x在表达式中,其结果的类型可以立即推断为 string因为只有一种方法需要考虑,它的返回类型是string .

关于c# - 动态、linq 和 Select(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5879900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com