我只注意到.NET允许我们做这样的。
I just noticed .net allows us to do like this.
public void Func1(ref String abc)
{
}
我在想,裁判的文章让任何意义????因为String是一个类(引用类型)
I was wondering "ref" keyword makes any sense???? as String is a Class(reference type)
这是任何不同。
public void Func1(String abc)
{
}
我只是问,因为我很困惑。无论是丢失了一些概念或他们是同一个东西,裁判关键字在这方面没有任何意义。
I am just asking as i am confused. either missing some concept or they are one and the same thing and "ref" keyword has no sense in this context.
参数由值通过默认。如果您传递参数给方法,原来的变量不被修改。如果你传递一个参数作为 REF
参数虽然,你通过在原来的变量可以被修改。
Parameters are passed by value by default. If you pass a parameter into a method, the original variable does not get modified. If you pass a parameter as a ref
parameter though, the original variable that you passed in can get modified.
试试这个:
public void Func1(String abc) {
abc = "Changed from Func1";
}
public void Func2(ref String abc) {
abc = "Changed from Func2";
}
public void main() {
string foo = "not changed";
Func1(foo);
Console.WriteLine(foo);
Func2(ref foo);
Console.WriteLine(foo);
}
你会得到的输出是:
The output you will get is:
not changed
Changed from Func2
在 FUNC1
富
的副本创建的,它指的是相同的字符串。但只要你为它指定另一个值,参数农行
引用另一个字符串。 富
不被修改,并仍然指向相同的字符串。
在 FUNC2
你传递一个引用富
,所以当你分配农行
一个新的值(即引用另一个字符串),你真的分配富
新值。
In Func1
a copy of foo
is created, which refers to the same String. But as soon as you assign it another value, the parameter abc
refers to another String. foo
is not modified and still points to the same string.
In Func2
you pass a reference to foo
, so when you assign abc
a new value (i.e. a reference to another string), you are really assigning foo
a new value.