如何将ref / out变量传递给函数外的另一个类变量; [英] How to pass a ref/out variable to another class variable outside the function;

查看:67
本文介绍了如何将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.

Use object instead of int.
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 the ref parameter.


这篇关于如何将ref / out变量传递给函数外的另一个类变量;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆