我可以定义一个委托(delegate)并像这样编写查询。
Func<string, bool> filter = s => s.Length == 5;
IEnumerable<string> query = names.Where(filter)
.Select(x => x.ToUpper());
我的问题是,如果
Func<T, TResult>
是一个将字符串作为参数并返回 bool 值的委托(delegate),为什么我不能说:delegate bool D(string s);
D d = new D(delegate(string s) { return s.Length == 1; });
IEnumerable<string> query = names.Where(d).Select...
?
最佳答案
因为它们是不同的类型。
给出相同类型错误的较短版本:
delegate bool D(string s);
delegate bool F(string s);
D d = new D(delegate(string s) { return s.Length == 1; });
F f = d;
Error 1 Cannot implicitly convert type 'Program.D' to 'Program.F'
以及扩展方法
Where
定义为Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
所以你需要一个
Func<string, bool>
和 D
相似但不兼容。
关于linq - 在 where 子句中委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10243458/