.NET中的参数ref
和out
参数有什么区别?一个人比另一个人更有用的情况是什么?什么是一个可以使用而另一个不能使用的代码片段?
当我对一个out
或ref
参数进行赋值时,是否会立即将值赋给调用者提供的引用,还是在方法返回时分配给引用的out
和ref
参数值?如果方法抛出异常,则返回值吗?
例如:
int callerOutValue = 1;
int callerRefValue = 1;
MyMethod(123456, out callerOutValue, ref callerRefValue);
bool MyMethod(int inValue, out int outValue, ref int refValue)
{
outValue = 2;
refValue = 2;
throw new ArgumentException();
// Is callerOutValue 1 or 2?
// Is callerRefValue 1 or 2?
}
Run Code Online (Sandbox Code Playgroud)