[英]How to use delegate as invoke parameter?
How do I give an action delegate as a parameter into invoke: 我如何给动作委托作为参数来调用:
class C {
static void A {}
public static void F(Action action) { action(); }
}
Now I can call F directly: 现在,我可以直接致电F:
F(A);
But how do I do the same with an invoke. 但是,我该如何执行调用。 The following does not compile: 以下内容无法编译:
MethodInfo methodInfo = typeof(C).GetMethod("F", BindingFlags.Static |
BindingFlags.NonPublic);
methodInfo.Invoke(null, new object[]{ A });
Neither does anything else I have tried like: 我尝试过的其他任何事情都没有:
methodInfo.Invoke(null, new object[]{ C.A });
methodInfo.Invoke(null, new object[]{ () => C.A() });
The compiler says it cannot convert the parameter into "object". 编译器表示无法将参数转换为“对象”。
尝试这个
methodInfo.Invoke(null, new object[] { new Action(C.A) });
First of all your code has a few problems: 首先,您的代码有一些问题:
1- Method CA
should be declared public
in order to be used outside. 1-方法CA
应该声明为public
以便在外部使用。
2- BindingFlags.NonPublic
is preventing to access method 'F'
since it is public
. 2- BindingFlags.NonPublic
禁止访问方法'F'
因为它是public
。 Use BindingFlags.Public
instead. 请改用BindingFlags.Public
。
Now, you can do as: 现在,您可以执行以下操作:
methodInfo.Invoke(null, new object[] { new Action(() => { C.A(); }) });
Specifically, to update label1 in another thread, use the Invoke with arguments with a Lambda statement and the parameters the Func requires. 具体来说,要在另一个线程中更新label1,请使用带有Lambda语句和Func所需参数的Invoke。
Int32 c = 0;
Int32 d = 0;
Func<Int32, Int32,Int32> y;
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); return x1++; }, c,d));
d++;
Generically, replace label1 by methodInfo. 通常,将label1替换为methodInfo。 Use Func. 使用功能。 With Action you can't pass arguments. 使用Action,您无法传递参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.