【问题标题】:Delegate in a where clause在 where 子句中委托
【发布时间】:2012-04-20 09:22:25
【问题描述】:

我可以定义一个委托并像这样编写查询。

Func<string, bool>   filter  = s => s.Length == 5;

IEnumerable<string> query = names.Where(filter)                                  
                                 .Select(x => x.ToUpper());

我的问题是,如果Func&lt;T, TResult&gt; 是一个将字符串作为参数并返回布尔值的委托,我为什么不能说:

delegate bool D(string s);
D d = new D(delegate(string s) { return s.Length == 1; });

IEnumerable<string> query = names.Where(d).Select...

?

【问题讨论】:

    标签: linq delegates where-clause lambda


    【解决方案1】:

    因为它们是不同的类型。

    给出相同类型错误的较短版本:

    delegate bool D(string s);
    delegate bool F(string s);
    
    D d = new D(delegate(string s) { return s.Length == 1; });
    F f = d;
    

    错误 1 ​​无法将类型“Program.D”隐式转换为“Program.F”

    而扩展方法Where定义为

    Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
    

    所以你需要一个Func&lt;string, bool&gt; 和D 相似但不兼容。

    【讨论】:

      【解决方案2】:

      这是因为两种不同的委托类型(Func&lt;TSource, TResult&gt; 也是委托类型)被认为是不同的类型,即使它们的签名相同。

      【讨论】:

        【解决方案3】:

        即使它们兼容,它们也不是同一类型。

        你需要“投射”它:

        var query = names.Where(new Func<string, bool>(d))
        

        我通常只是这样做:

        var query = names.Where(x => d(x))
        

        【讨论】:

        • 唯一真正帮助 SO 实现目标的人,哈哈
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多