执行给定方法的 C# 方法
我正在尝试编写以下内容:我想编写一个方法“A”,它采用另一个方法“B”作为参数,以及该方法 B 的未知数量的参数。(params object[] args)。现在,在方法 A 中,我想使用参数 args 调用 B。 B 现在将返回一个我希望 A 也返回的对象。
这一切听起来有点奇怪,因此我将添加一些示例代码:
public object A(Func<object> B, params object[] args)
{
object x = B.Method.Invoke(args);
return x;
}
问题是,Func 不能像那样工作。有谁知道这样做的方法吗?
问候, 基督教
I am trying to write the following: I would like to write a method "A" which takes as parameter another method "B" as well as an unknown number of parameters for this method B. (params object[] args). Now, inside method A i would like to make a call to B with the parameters args. B will now return an object which I would like A to return as well.
This all sounds a bit strange, therefore I will add some example code:
public object A(Func<object> B, params object[] args)
{
object x = B.Method.Invoke(args);
return x;
}
The problem is, that Func does not work like that. Does anyone know a way of doing this?
Regards,
Christian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
...再见类型安全
...goodbye type-safety
Func
Func<object>
is a delegate for a method that takes no arguments and returnsobject
. If you change it toFunc<object,object>
, it will take an argument and return object:这应该可以做到:
This should do it:
您应该有这样的代码:
您缺少 Func 重载需要接受参数的对象数组。
无论如何,如果您需要此方法“A”来接受无参数函数,则应该创建“A”的无参数函数参数重载。
You should have a code like this one:
You're missing that the Func overload needs to accept your object array of arguments.
Anyway, if you need this method "A" to accept parameterless functions, you should create a paremeterless function parameter overload of "A".