【问题标题】:Convert Expression<Func<IBar, T>> to Expression<Func<Bar, T>>将 Expression<Func<IBar, T>> 转换为 Expression<Func<Bar, T>>
【发布时间】:2014-04-25 21:43:43
【问题描述】:

当 Bar 实现 IBar 时,如何从 Expression&lt;Func&lt;IBar, T&gt;&gt; 转换为 Expression&lt;Func&lt;Bar, T&gt;&gt;

这个更通用的问题有答案:

Convert Expression<Func<T1,bool>> to Expression<Func<T2,bool> dynamically

在这种情况下,这是最好的方法吗?鉴于 Bar 实现了 IBar,难道没有更简单的方法吗?

所以,给定这个人为的示例代码:

          public class Foo<T>
          {
                 private readonly List<T> _list = new List<T>();

                 public void Add(T item)
                 {
                       _list.Add(item);
                 }

                 public bool AnyFunc(Func<T, bool> predicate)
                 {
                       return _list.Any(predicate);
                 }

                 public bool AnyExpression(Expression<Func<T, bool>> expression)
                 {
                       return _list.AsQueryable().Any(expression);
                 }                    
          }

          public interface IBar
          {
                 string Name { get; }
          }

          public class Bar : IBar
          {
                 public string Name { get; set; }
          }

这说明了问题:

          public class Test()
          {
                 private Foo<Bar> _foobar = new Foo<Bar>(); 

                 public void SomeMethodFunc(Func<IBar, bool> predicate)
                 {
                       // WILL COMPILE AND WORKS, casts from Func<IBar, bool> to Func<Bar, bool>
                       var found = _foobar.AnyFunc(predicate);
                 }

                 public void SomeMethodExpression(Expression<Func<IBar, bool>> expression)
                 {
                       // WON'T COMPILE - Can't cast from Expression<Func<IBar, bool>> to Expression<Func<Bar, bool>>  
                       var found = _foobar.AnyExpression(expression);
                 }
          }

有什么想法可以完成类似于 SomeMethodExpression 的事情吗?

【问题讨论】:

  • 你看过AutoMapper吗?根据您的用例,QueryableExtensions 命名空间可能会解决您的问题。但是如果没有看到你在一个非人为的例子中如何使用Func&lt;Foo, T&gt;,就不能肯定地说。
  • 我不明白这个问题。从您的代码来看,您似乎在说“我这样做,它有效。我做另一件事,但它没有。”。如果一种方法有效,为什么还要担心另一种方法?
  • @LasseV.Karlsen:工作的一个使用委托,另一个使用表达式树。
  • 你不理解我的评论/问题。你说的是:a 有效,b 无效。为什么不能使用?

标签: c# linq lambda


【解决方案1】:

由于这种情况很简单,并且只涉及“铸造”问题,所以有一个捷径:

public void SomeMethodExpression(Expression<Func<IBar, bool>> expression)
{
    Expression<Func<Bar, bool>> lambda = Expression.Lambda<Func<Bar, bool>>(expression.Body, expression.Parameters);
    var found = _foobar.AnyExpression(lambda);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多