如何获得Generic Func< T>的方法名称传入方法 [英] How to get Method Name of Generic Func<T> passed into Method

查看:107
本文介绍了如何获得Generic Func< T>的方法名称传入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



方法签名

$ b使用.Net闭包传递给对象的方法名称如下:


$ b

  public IEnumerable< T> GetData< T>(Func< IEnumerable< T> WebServiceCallback)
其中T:class
{
//获取我'< LoadData> b__3'
var a = nrdsWebServiceCallback.Method.Name;
var b = nrdsWebServiceCallback.GetInvocationList();

返回WebServiceCallback();
}

我这样称呼它:

  SessionStateService.Labs = CacheManager.GetData((=)=> 
WCFService.GetLabs(SessionStateService.var1,SessionStateService.var2));

看到'b__3'而不是WCFServce.GetLabs(..)等$ b $您正在查看lambda表达式(由编译器生成)的名称,而不是lambda中调用的方法的名称。



您必须使用< Expression< Func< T>> 来代替 FUNC< T>

试试

  public IEnumerable< T> GetData< T>(Expression< Func< IEnumerable< T>> callbackExpression)
其中T:class
{
var methodCall = callbackExpression.Body as MethodCallExpression;
if(methodCall!= null)
{
string methodName = methodCall.Method.Name;
}

return callbackExpression.Compile()();
}


I'm trying to get the method name of a function passed into an object using a .Net closure like this:

Method Signature

public IEnumerable<T> GetData<T>(Func<IEnumerable<T>> WebServiceCallback) 
where T : class    
{
    // either gets me '<LoadData>b__3'
    var a = nrdsWebServiceCallback.Method.Name;
    var b = nrdsWebServiceCallback.GetInvocationList();

    return WebServiceCallback();
}

I'm calling it like this:

SessionStateService.Labs = CacheManager.GetData(() =>  
WCFService.GetLabs(SessionStateService.var1, SessionStateService.var2));

Seeing 'b__3' instead of WCFServce.GetLabs(..) etc

解决方案

You're looking at the name of the lambda expression (generated by the compiler), instead of the name of the method called inside the lambda.

You have to use an <Expression<Func<T>> instead of a Func<T>. Expressions can be parsed and analyzed.

Try

public IEnumerable<T> GetData<T>(Expression<Func<IEnumerable<T>>> callbackExpression) 
where T : class    
{
    var methodCall = callbackExpression.Body as MethodCallExpression;
    if(methodCall != null)
    {
        string methodName = methodCall.Method.Name;
    }

    return callbackExpression.Compile()();
}

这篇关于如何获得Generic Func&lt; T&gt;的方法名称传入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆