问题描述
我正在寻找一个清晰,简洁和准确的答案。
I'm looking for a clear, concise and accurate answer.
虽然可以链接到很好的解释,但实际上是实际的答案。
Ideally as the actual answer, although links to good explanations welcome.
这也适用于VB.Net ,但关键字不同- ByRef
和 ByVal
。
This also applies to VB.Net, but the keywords are different - ByRef
and ByVal
.
推荐答案
默认情况下(在C#中),将对象传递给函数实际上会将引用的副本传递给该对象。更改参数本身只会更改参数中的值,而不会更改指定的变量。
By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.
void Test1(string param)
{
param = "new value";
}
string s1 = "initial value";
Test1(s1);
// s1 == "initial value"
使用 out
或 ref
传递对函数调用中指定的变量的引用。 out
或 ref
参数的值的任何更改都将传递回调用方。
Using out
or ref
passes a reference to the variable specified in the call to the function. Any changes to the value of an out
or ref
parameter will be passed back to the caller.
out
和 ref
的行为相同,只是略有不同: ref
参数需要在调用之前进行初始化,而 out
参数可以未初始化。通过扩展,保证 ref
参数在方法开始时被初始化,而 out
参数被视为未初始化
Both out
and ref
behave identically except for one slight difference: ref
parameters are required to be initialised before calling, while out
parameters can be uninitialised. By extension, ref
parameters are guaranteed to be initialised at the start of the method, while out
parameters are treated as uninitialised.
void Test2(ref string param)
{
param = "new value";
}
void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}
string s2 = "initial value";
string s3;
Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"
编辑 :如指出, out
和 ref
之间的差异仅由C#编译器而不是CLR强制执行。据我所知,VB没有等效于 out
并实现了 ref
(如 ByRef
),与CLR的支持相匹配。
Edit: As dp points out, the difference between out
and ref
is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for out
and implements ref
(as ByRef
) only, matching the support of the CLR.
这篇关于ref,val和out对方法参数意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!