如何将实现了IBar的Bar类型中的
针对这个问题,以下是更加通用的解决方案: Convert Expression<Func<T1,bool>> to Expression<Func<T2,bool> dynamically 在此情况下,这是否是最佳方法?考虑到Bar实现了IBar,难道没有更简单的方法吗?
因此,考虑到这个人为构造的代码示例:
这是一个示例,说明了问题:
有什么想法可以实现类似于SomeMethodExpression的功能吗?
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的功能吗?
Func<Foo, T>
,就不能确定。 - Scott Chamberlain