功能参数数量未知 [英] Func<> with unknown number of parameters

查看:29
本文介绍了功能参数数量未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下伪代码:

TResult Foo<TResult>(Func<T1, T2,...,Tn, TResult> f, params object[] args)
{
    TResult result = f(args);
    return result;
}

该函数接受具有未知数量的通用参数和相应参数列表的 Func<>.可以用C#写吗?如何定义和调用Foo?如何将 args 传递给 f?

The function accepts Func<> with unknown number of generic parameters and a list of the corresponding arguments. Is it possible to write it in C#? How to define and call Foo? How do I pass args to f?

推荐答案

那是不可能的.充其量,您可以拥有一个也接受可变数量参数的委托,然后让委托解析参数

That's not possible. At best, you could have a delegate that also takes a variable number of arguments, and then have the delegate parse the arguments

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


Foo<int>(args =>
{
    var name = args[0] as string;
    var age = (int) args[1];

    //...

    return age;
}, arg1, arg2, arg3);

这篇关于功能参数数量未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆