Func<> with unknown number of parameters

前端 未结 6 1513
独厮守ぢ
独厮守ぢ 2020-12-06 00:37

Consider the following pseudo code:

TResult Foo(Func f, params object[] args)
{
    TResult result = f(args);
           


        
6条回答
  •  有刺的猬
    2020-12-06 01:23

    You can use Delegate with DynamicInvoke.

    With that, you don't need to handle with object[] in f.

    TResult Foo(Delegate f, params object[] args)
    {
        var result = f.DynamicInvoke(args);
        return (TResult)Convert.ChangeType(result, typeof(TResult));
    }
    

    Usage:

    Func f = (name, age, active) =>
    {
        if (name == "Jon" && age == 40 && active)
        {
            return true;
        }
        return false;
    }; 
    
    Foo(f,"Jon", 40, true);
    

    I created a fiddle showing some examples: https://dotnetfiddle.net/LdmOqo


    Note:

    If you want to use a method group, you need to use an explict casting to Func:

    public static bool Method(string name, int age)
    {
        ...
    }
    var method = (Func)Method;
    Foo(method, "Jon", 40);
    

    Fiddle: https://dotnetfiddle.net/3ZPLsY

提交回复
热议问题