2016-11-22 155 views
1

metthod以表达我所说的方法与表达,这最后一个记录返回表:呼叫通过反射

public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null) 
{ 
    return specification == null 
     ? Set().LastOrDefault() 
     : Set().OrderBy(specification).LastOrDefault(); 
} 

通过反射

var methodCreateReadRepositoryAttr = (entityMetadata.GetEntityAttributeType() != null) ? 
typeof(IRepositoryFactory).GetMethod("CreateReadRepository").MakeGenericMethod(entityMetadata.GetEntityAttributeType()) : null; 

    var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast"); 
var closedGenericMethod = methodEntity3.MakeGenericMethod(new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) }; 

Expression <Func<ArticleAttribute, int>> articleReturnExpression = e => e.ArticleAttributeID; 

var fromRepo3 = closedGenericMethod.Invoke(attributeReadRepository, new object[] {articleReturnExpression}); 

在最后一行我有错误讯息

对象类型'System.Linq.Expressions.Expression 1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute,System.I nt32]]'无法转换为类型'System.Linq.Expressions.Expression 1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute,System.Linq.Expressions.Expression 1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute, System.Int32]]]]”。

+0

是如何从https://stackoverflow.com/questions/40737230/call-generic-method-with-expression-through-reflection这有什么不同? –

+0

这是apear的下一个问题。抱歉! –

+2

请提供一个[mcve],以便您可以得到一个我们可以显示*一直工作的答案。它不能帮助任何人一次解决一个小问题,当我们提供一个完整的例子时,我们可以提供一个完整的解决方案。 –

回答

1

您正在将泛型参数类型与方法参数类型混合。

你的方法唯一的通用参数

public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null) 

TKey。因此

var closedGenericMethod = methodEntity3.MakeGenericMethod(
    new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) }); 

应该

var closedGenericMethod = methodEntity3.MakeGenericMethod(
    new Type[] { typeof(int) });