通过反射调用通用方法 [英] Call generic method with Expression through reflection
本文介绍了通过反射调用通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public T FindLast< TKey>(Expression< ; Func< T,TKey>> specification = null)
{
返回规范== 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,new Type [] {typeof(Expression< Func< ArticleAttribute,int>)});
但在调试中,$ code> methodEntityGet3 为null。我做错了什么?
解决方案
你需要打破你的方法调用两个:
var methodEntityGet3 = attributeReadRepository.GetType()。GetMethod(FindLast);
var closedGenericMethod = methodEntity3.MakeGenericMethod(new Type [] {typeof(Expression< Func< ArticleAttribute,int>>)};
I have a generic method which should return the last record from a table:
public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null)
{
return specification == null
? Set().LastOrDefault()
: Set().OrderBy(specification).LastOrDefault();
}
I need to call it through reflection
var methodCreateReadRepositoryAttr = (entityMetadata.GetEntityAttributeType() != null) ?
typeof(IRepositoryFactory).GetMethod("CreateReadRepository").MakeGenericMethod(entityMetadata.GetEntityAttributeType()) : null;
var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast", new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) });
But in debug methodEntityGet3
is null. What did I do wrong?
解决方案
You need to break your method calling in to two:
var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast");
var closedGenericMethod = methodEntity3.MakeGenericMethod(new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) };
这篇关于通过反射调用通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文