【发布时间】:2014-05-03 18:28:17
【问题描述】:
关于 C# 的基本手册规定,要在传递给另一个方法时更改值类型,您必须使用 out 或 ref 关键字等。
例如:
int Loop(int counter)
{
return(++counter);
}
void ClickIt ()
{
int count = 0;
for (int c1 = 0; c1 < 10; c1++)
{
count = Loop(count);
Console.Writeline(count);
}
}
这里,ClickIt 输出以下结果:1, 2, 3, 4, ... 10
在示例中,count(一个值类型)从方法 ClickIt 传递到方法 Loop 没有 out 或 ref更改为Loop。然后Loop 将count 返回到调用方法ClickIt,该方法将更改为count。
所以,我的问题是:值类型何时作为参数传递给另一个方法时,需要使用out 或ref 以便可以更改值?
【问题讨论】:
-
对象通过 ref 传递,对于 struct 和基本数据类型,它是通过 val 除非指定了 out 或 ref
-
这些更改不通过
Loop的参数传回。更改将写入您的count变量,因为您明确分配了Loop的返回值。
标签: c# methods parameter-passing value-type