开发者

How do I send a parameter list to be used as arguments when a delegate is invoked?

I've implemented a simple extension method in my asp.net mvc 3 app to pull objects out of session using generics:

public static T GetVal<T>(this HttpSessionStateBase Session, string key, Func<T&开发者_JS百科gt; getValues)
    {
        if (Session[key] == null)
            Session[key] = getValues();

        return (T)Session[key];
    }

This works great if getValues() doesn't require any arguments.

I was attempting to write an overload that takes in params object[] args to allow me to pass arguments if necessary to the getValues() function, but I don't know what the syntax is to apply those variables to the function.

Is this even possible? Thanks in advance for your advice.


I would argue that you shouldn't need to do this - the caller can handle that with a lambda expression. For example:

int x = session.GetVal<int>("index", () => "something".IndexOf("o"));

Here we're capturing the idea of calling IndexOf on "something" passing in the argument "o". All of that is captured in a simple Func<int>.


You can add an overload to your function

public static T GetVal<T>(this HttpSessionStateBase Session, string key, Func<IList<object>,T> getValues, IList<object> args)
{
    if (Session[key] == null)
        Session[key] = getValues(args);

    return (T)Session[key];
}


You'll have to define your own delegate rather than Func. The following will work perfectly here:

public delegate TResult ParamsFunc<TResult>(params object[] args);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜