我有以下接口:
public interface IHasSchoolId
{
long? SchoolId { get; set; }
}
并且以下实体:
public class Student : IHasSchoolId
{
long? SchoolId { get; set; }
}
接下来是实现空接口 IEntityManager<T>
的以下实体管理器:
public class HasSchoolIdManager: IEntityManager<IHasSchoolId>
{
public static Expression<Func<IHasSchoolId, bool>> Filter()
{
return x=> x.SchoolId != null; //this is just an example
}
}
最后,我有以下方法:
private Expression<Func<TEntity, bool>> GetFilters<TEntity>()
{
Expression<Func<TEntity, bool>> result = null;
var entityManagers = //geting entitymanagers that are assinable to TEntity, like the one above and a lot more like IEntityManager<Student> itself
foreach (var entityManager in entityManagers)
{
var filterMethod = entityManager.GetMethod("Filter");
if (filterMethod != null)
result = AndAlso(result, (Expression<Func<TEntity, bool>>) filterMethod.Invoke(null, null)); //this line throws exception
}
return result;
}
当我像 GetFilters<Student>()
这样调用方法时,我会遇到以下异常:
System.InvalidCastException:“无法将类型为'System.Linq.Expressions.Expression[System.Func[WebCore.Models.Infrastructure.Interfaces.IHasSchoolId,System.Boolean]]'的对象强制转换为类型'System.Linq.Expressions.Expression[System.Func[WebCore.Models.Student,System.Boolean]]'。”
顺便说一下,这是我的 AndAlso 方法,它可以正常工作:
private Expression<Func<T, bool>> AndAlso<T>(
Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
if (expr1 == null)
return expr2;
if (expr2 == null)
return expr1;
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}
这是我的空IEntityManager接口:
public interface IEntityManager<T>
{
}
注意:并非所有实体都实现了IHasSchoolId接口,还有许多其他接口,这只是一个示例。
我想我的问题是,如何将Expression<Func</*一个接口*/, bool>>
强制转换为 Expression<Func</*实现该接口的类*/, bool>>
,
使用反射调用过滤器方法,因为你可以看到,我正在使用反射调用过滤器方法。
IEntityManager
接口。 - codejockiepublic interface IEntityManager<TEntity> where TEntity : IHasSchoolId
。 - Racil Hilan{ public Expression> forCurrentUser;
public FilterQueryable(UserValues userValues)
{
forCurrentUser = p => p.CreatorId == userValues.Identifier;
}
}```
- flieks