我发现这里类似的问题 How can I find the method that called the current method? 但在这个问题的答案也给予同样的结果,因为我在我的第一个例子中所提到的如何获取方法名称作为参数传递给函数?
这里是方法,我使用
public class iStore
{
public T GetSiteCacheValueByFunc<T>(Func<T> func) where T : class
{
var methodName = func.Method.Name;
}
}
这里我使用iStore.GetSiteCacheValueByFunc
使用下面的代码,我得到方法名<Index>b_2
,而我应该得到GetAllLanguages
public ActionResult Index()
{
var site = BusinessLogic.Caching.iStore;
var languages = site.GetSiteCacheValueByFunc<IEnumerable<Language>>(() => LanguageManager.GetAllLanguages());
}
如果我使用下面的代码我得到正确的方法名GetAllLanguages
但这种方式我不能传递参数给GetAllLanguages方法
public ActionResult Index()
{
var site = BusinessLogic.Caching.iStore;
var languages = site.GetSiteCacheValueByFunc<IEnumerable<Language>>(LanguageManager.GetAllLanguages);
}
我哪里做错了吗?以及我如何得到正确的methodName?
在你的第二个例子,你正在传递一个匿名函数,所以像' b_2'的名称也就不足为奇了。但是为什么你首先需要方法名? –
2014-09-23 11:40:49
我想过滤特定方法 – 2014-09-23 11:42:01
代码不应该根据谁调用它来改变其行为。 – CodeCaster 2014-09-23 11:47:44