如何将ref / out变量传递给函数外的另一个类变量;
如何为函数外部的类存储ref / out变量;
请考虑以下代码:
How to store a ref/out variable for the class outside the function;
Consider the following code:
class test
{
int data;
test(ref int orig)
{
this.data=orig;//this would pass the value of orig to data.
}
button1_Click(object sender, EventArgs e)
{
//here the value of orig has to be stored. Now if i do:
data=1;
// will 1 be passed to orig which is passed from another class?
}
但是我想在类中存储orig'的引用,因为这个类是一个表单,稍后点击一个按钮就会设置值在原点。现在按钮点击事件功能必须设置值。
but i want to store the orig''s refernce in the class as this class is a form, and later on on a button click the value will be set in the orig. Now Button click event function has to set the value.
否。int
是值类型,而不是引用。所以当你执行
No.int
is a value type, not a reference. So when you execute
this.data = orig;
中的值 orig
被复制到数据
,而不是对原始位置的引用。 (引用不是指针,虽然它们大部分时间都看起来像。)
如果你重写了 test
另一种方法:
the value in orig
is copied into data
, not a reference to the original location. (References are not pointers, although they look like them most of the time).
If you rewrote your test
method to go the other way:
orig = this.data;
然后将更改调用方法中orig的值,但在 test
方法之外对 data
的后续更改将不改变它。
Then the value of orig in the calling method will be changed, but subsequent changes to data
outside the test
method will not change it.
框整数值。
使用对象
而不是int
。
例如对象数据
;
这将通过引用传递整数值,但需要一些类型转换 [ ^ ]。
另一种方法是继续使用ref
参数传递整数值(通过引用)。
Box the integer value.
Useobject
instead ofint
.
For e.g.object data
;
This will pass the integer value around by reference but will require some type casting[^].
The other way would be to continue to pass the integer value (by reference) around using theref
parameter.