为什么我可以 ref 返回只存在于方法内部的数组项? [英] Why can I ref return an item of an array that only exists inside the method?

查看:55
本文介绍了为什么我可以 ref 返回只存在于方法内部的数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 C#7 的新 ref 返回.

I was trying out the new ref returns of C#7.

我能够编译和构建这个:

I am able to compile and build this:

        public ref string MisUseRefReturn(int index)
    {
        string[] array = { "a", "b", "c", "d" };
        return ref array[index]; //array[2] gets out of scope when this method returns!
    }

根据MSDN:返回值不能是返回它的方法中的局部变量;它必须有一个在返回它的方法之外的范围.它可以是类的实例或静态字段,也可以是传递给方法的参数.尝试返回局部变量会生成编译器错误 CS8168,无法通过引用返回本地 'obj',因为它不是 ref 本地."

According to MSDN: The return value cannot be a local variable in the method that returns it; it must have a scope that is outside the method that returns it. It can be an instance or static field of a class, or it can be an argument passed to the method. Attempting to return a local variable generates compiler error CS8168, "Cannot return local 'obj' by reference because it is not a ref local."

那么为什么要编译呢?当我执行此方法时,返回的引用显示正确的字符串.

So why does this compile? When I execute this method, the returned reference shows the correct string.

推荐答案

查看说明 这里:

返回局部 int 变量而不是数组是不可能的.int 是值类型,因此变量在方法结束,因此无法返回对它的引用.这与数组不同.数组是一种引用类型,而数组在堆上分配.数组中的 int 可以是使用 ref 关键字返回.

Returning a local int variable instead of an array is not possible. int is a value type, and thus the variable gets out of scope at the end of the method, and thus a reference to it cannot be returned. That’s different with an array. An array is a reference type, and the array is allocated on the heap. An int within the array can be returned with the ref keyword.

您不能直接返回整数值,因为它是一种值类型.可以返回数组元素,因为它是引用类型.MSDN 声明是正确的.

You could not return an integer value directly as it is a value type. An array element can be returned because it is a reference type. The MSDN statement is correct.

... 只存在于方法内部的数组

... of an array that only exists inside the method

返回的引用在方法调用之外保留数组.

The returned reference persists the array beyond the method call.

这篇关于为什么我可以 ref 返回只存在于方法内部的数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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