我有一段代码:
方法如下:
public IEnumerable<c> Test(){
var collection = new a();
IEnumerable<c> bs = collection.Where(item => item.Id > 10).Select(item => item);
return from item in collection
where item.Id > 10
select item;
}
Run Code Online (Sandbox Code Playgroud)
(前两行编译好)
它没有编译并失败:
无法隐式转换
System.Collections.Generic.IEnumerable<Stackoverflow.b>为System.Collections.Generic.IEnumerable<Stackoverflow.c>
但是下面的代码编译得很好:
return from item in collection
where item.Id > 10
select new b(null);
Run Code Online (Sandbox Code Playgroud)
因为select子句中表达式的类型是相同的,我希望它在两种情况下都能编译,或者两者都失败.
如果我使用方法语法而不是查询comprehesion并写:
collection.Where(item => item.Id > 10).Select(item => item)
Run Code Online (Sandbox Code Playgroud)
太编译了
我的问题是" 宇宙有什么问题 "(这是一个编译器错误)还是我错过了什么?
编辑
我没有using System.Linq这样的正常选择和哪些方法不起作用只有下面的代码是学术练习的一部分,试图拉伸LINQ的基于模式的方法重载决议.签名是刻意的奇怪/令人惊讶的,其中包括一个投影,但我相信这通常是一个非常糟糕的主意.
编辑
有问题的类的定义和选择扩展方法
public static class Enumerable {
public static IEnumerable<c> Select(this IEnumerable<b> self, Func<b,b> selector){
return null;
}
}
public class a{
public IEnumerable<b> Where(Predicate<a> predicate){
return null;
}
public int Id { get; set; }
}
public class b{
}
public class c{
}
Run Code Online (Sandbox Code Playgroud)
这都是关于查询表达式的翻译.您可能需要查看C#语言规范4.0 7.16.2(或C#3.0的7.15.2)以获取更多详细信息,但简而言之,表达式如下:
from x in c
where f(x)
select x
被翻译为
c.Where(x => f(x))
所以你的Enumerable.Select不会被调用,你将获得IEnumerable <b>而不是IEnumerable <c>.究竟编译器在抱怨什么.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |