Control.Invoke和ref参数 [英] Control.Invoke and ref parameter
问题描述
有谁知道Control.Invoke如何调用一个有参考的方法?
参数?
例如,
Hi,
Does anyone know how Control.Invoke can invoke a method which has ref
parameters?
For example,
class A {
public delegate MyFuncHandler(ref int i, ref int j);
public void MyFunc(ref int i, ref int j)
{
..
}
public A
public void MyCaller(DataGridView oDataGridView)
{
int x = 1;
int y = 1;
...
oDataGridView.Invoke(new MyHandler(MyFunc), new object { ref x, ref y });
....
}
oDataGridView.Invoke(new MyHandler(MyFunc), new object { ref x, ref y });
产生编译错误。我这样做错了,或者Control.Invoke确实
不允许使用ref参数的方法?
谢谢
produces compilation error. Am I doing this wrong, or Control.Invoke does
not allow method with ref parameters?
Thanks
推荐答案
Control.Invoke
的重载具有params
对象数组的重载。params
参数允许直接传递可变数量的元素,而无需将它们显式打包到数组中。
在参数中,你无法传递参考。但请记住,如果您传递参考类型,它们按照定义参考参数。即无论你修改里面,调用都会对传递的引用类型参数产生影响。
假设你有实例传递给调用的引用类型(不是值类型),您的调用如下所示:
The overload ofControl.Invoke
has an overload with aparams
object array. Theparams
parameter allows to pass a variable number of elements directly without the need to explicitly pack them into an array.
In params, you cannot pass references. But keep in mind that if you pass reference types, that they are by definition reference paramater. I.e. whatever you modify inside the invocation has an effect to the passed reference type parameters.
Assuming you have instances of reference types (not value types) that you pass to the invocation, your call looks like this:
oDataGridView.Invoke(new MyHandler(MyFunc), x, y);
甚至
or even
oDataGridView.Invoke(MyFunc, x, y);
另一方面,如果您需要将多个值类型值作为引用传递,您可以将它们打包到某种容器中并传递容器(这是a 引用类型)到处理程序。如果它是同源类型(所有相同的类型),请使用 System.Collections.Generic
命名空间中的任何集合。如果它是不均匀的类型(并非所有类型都相同),请使用元组
或创建自己的特定参数类(例如,类派生类)来自 EventArg
,就像 EventHandler
中使用的那样。
干杯
Andi
On the other hand, if you need to pass multiple value types values as references, you can pack them into some kind of container and pass the container (which is a reference type) to the handler. If it's homogenous types (all the same type), use any of the collections from System.Collections.Generic
namespace. If it is inhomogenous types (not all types are the same), use a Tuple
or create your own specific argument class (e.g. like a class derived from EventArg
like the ones used in EventHandler
s).
Cheers
Andi
这篇关于Control.Invoke和ref参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!