转换表达式<func <ibar,t =“”>&gt;表达式<func <bar,t =“”>&gt; </func <bar,> </func <ibar,>

时间:2014-04-25 21:43:43

标签: c# linq lambda

当Bar实施IBar时,如何从Expression<Func<IBar, T>>转换为Expression<Func<Bar, T>>

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

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的东西吗?

1 个答案:

答案 0 :(得分:5)

由于这个案例很简单并且仅与“投射”问题有关,因此有一个捷径:

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);
}