如何捕获通过lambda传递的方法参数?

时间:2013-02-12 18:42:16

标签: c# reflection lambda func

我在Web API基本控制器中有一个泛型方法,我在其中传入一个Func 如果可能的话,我想以某种方式来限制lambda中使用的回调方法的参数......

为了说明,请参阅以下代码

public class StuffController : BaseController
{
    // method #1
    [HttpGet]
    public async Task<HttpResponseMessage> GetWidget(int id)
    {
        return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id));
    }

    // method #2
    [HttpGet]
    public async Task<HttpResponseMessage> GetWidget(int year, int periodId, int modelId, int sequenceId)
    {
        return await ProcessRestCall(async rc => await rc.GetWidgetAsync(year, periodId, modelId, sequenceId));
    }

    // method #3
    [HttpGet]
    public async Task<HttpResponseMessage> DecodeWidget(string sid)
    {
        return await ProcessRestCall(async rc => await rc.GetIdsAsync(sid));
    }
}


public class BaseController : ApiController
{
    [NonAction]
    protected async Task<HttpResponseMessage> ProcessRestCall<T>(Func<RestClient, Task<T>> restClientCallback) where T : class
    {
        // stuff happens...

        // TODO: here I'd like to capture parameters (and their types) of the await methods passed to restClientCallback via lambdas...
        // for example, in case of method #2 I would  get params object [] containing year, periodId, modelId, sequenceId
        T result = await restClientCallback(restClient);

        // more stuff...
        var response = Request.CreateResponse(HttpStatusCode.OK, result);        
        return response;
    }
}

更新(“为什么这样做?”)

上面的ProcessRestCall方法做了很多事情,但主要是它登录,获取数据,注销...我有一个简单的小内存缓存,我想在登录后使用它来返回数据并提高性能。我无法控制“休息客户端”及其行为方式。我的WidgetCache包装System.Runtime.Caching.MemoryCache并使用“typeof(T)-id(-id)*”作为字符串缓存键。生成缓存键我需要结果类型(我有),以及一个或多个相关的id(在labbda回调中作为参数传递)

可能的解决方法(可能更简洁的方法)

我可以捕获这些数据并将其作为参数发送到ProcessRestCall

public async Task<HttpResponseMessage> GetWidget(int id)
{
    var cacheKey = Cache.GenerateKeyFor(typeof(Widget), id);
    return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id), cacheKey);
}

0 个答案:

没有答案