当一个C#“出”或“参考”参数的值实际上返回到调用方? [英] When is the value of a C# 'out' or 'ref' parameter actually returned to the caller?

查看:201
本文介绍了当一个C#“出”或“参考”参数的值实际上返回到调用方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做一个分配到退出 REF 参数,立即分配给参考价值前提调用者,或者被分配到引用时,该方法会返回退出 REF 参数值?如果该方法抛出一个异常,正在返回的值?

例如:

  INT callerOutValue = 1;
INT callerRefValue = 1;
的MyMethod(123456,走出callerOutValue,裁判callerRefValue);

布尔的MyMethod(INT inValue,OUT INT outValue,楼盘INT REFVALUE)
{
    outValue = 2;
    REFVALUE = 2;

    抛出新的ArgumentException();

    //是callerOutValue 1或2?
    //是callerRefValue 1或2?
}
 

解决方案

由于 REF 退出参数允许方法与实际引用调用者传递的工作,所有的改动这些引用会立即反映到时,控制返回给调用者。

这意味着在你上面的例子(如果你赶上的ArgumentException )当然, outValue REFVALUE 将同时设置为2。

同样重要的是要注意,退出 REF 正处在一个IL级别相同的概念 - 它只是这需要一种方法将其值设置返回之前用C#编译器强制执行的额外排除。因此,从CLR的角度 outValue REFVALUE 有相同的语义,并处理方式相同。

When I make an assignment to an out or ref parameter, is the value immediately assigned to the reference provided by the caller, or are the out and ref parameter values assigned to the references when the method returns? If the method throws an exception, are the values returned?

For example:

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?
}

解决方案

Since ref and out parameters allow a method to work with the actual references that the caller passed in, all changes to those references are reflected immediately to the caller when control is returned.

This means in your example above (if you were to catch the ArgumentException of course), outValue and refValue would both be set to 2.

It is also important to note that out and ref are identical concepts at an IL level - it is only the C# compiler that enforces the extra rule for out that requires that a method set its value prior to returning. So from an CLR perspective outValue and refValue have identical semantics and are treated the same way.

这篇关于当一个C#“出”或“参考”参数的值实际上返回到调用方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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