考虑以下伪代码:
TResult Foo<TResult>(Func<T1, T2,...,Tn, TResult> f, params object[] args)
{
TResult result = f(args);
return result;
}
函数接受 Func<>
具有未知数量的通用参数和相应参数的列表。可以用C#写吗?如何定义和调用Foo
?我如何通过 args
至 f
?
最佳答案
您可以将 Delegate
与 DynamicInvoke
一起使用。
有了它,您就不需要处理 f
中的 object[]
。
TResult Foo<TResult>(Delegate f, params object[] args)
{
var result = f.DynamicInvoke(args);
return (TResult)Convert.ChangeType(result, typeof(TResult));
}
用法:
Func<string, int, bool, bool> f = (name, age, active) =>
{
if (name == "Jon" && age == 40 && active)
{
return true;
}
return false;
};
Foo<bool>(f,"Jon", 40, true);
我创建了一个显示一些示例的 fiddle :https://dotnetfiddle.net/LdmOqo
注意:
如果你想使用方法组
,你需要对Func
进行显式转换:
public static bool Method(string name, int age)
{
...
}
var method = (Func<string, int, bool>)Method;
Foo<bool>(method, "Jon", 40);
fiddle :https://dotnetfiddle.net/3ZPLsY
关于c# - 参数数量未知的 Func<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22834120/