Detailed explanation of ref locals and returns in C# 7.0

黄舟
Release: 2017-03-16 11:13:46
Original
1655 people have browsed it

This article mainly introduces the ref locals and returns of C# 7.0, that is, the local variables and reference returns, with It has a certain reference value. Interested friends can refer to it

If you haven’t read the original text, please move to: [Incoming news] New features of C#7.0 (available in VS2017)

Nonsense Without further ado, let’s get straight to the point. First of all, we know that the ref keyword changes value transfer into reference transfer, so let’s first take a look at ref locals (ref local variables)

The sub-code is as follows:


static void Main(string[] args)
  {

   int x = 3;
   ref int x1 = ref x; //注意这里,我们通过ref关键字 把x赋给了x1
   x1 = 2;
   Console.WriteLine($"改变后的变量 {nameof(x)} 值为: {x}");
   Console.ReadLine();

  }
Copy after login

This code eventually outputs "2"

Please pay attention to the comment part. We assign x to x1 through the ref keyword. If it is If the value type is passed, it will have no effect on The space that needs to be opened up.

Next let’s take a look

ref returns (ref reference return)

This function is actually very useful. We can treat the value type as Reference type to return.

Old rules, let’s give a chestnut, the code is as follows:

Very simple logic. Get the value of the specified subscript of the specified

array

static ref int GetByIndex(int[] arr, int ix) => ref arr[ix]; //获取指定数组的指定下标
Copy after login

We write the test code as follows:

   int[] arr = { 1, 2, 3, 4, 5 };
   ref int x = ref GetByIndex(arr, 2); //调用刚才的方法
   x = 99;
   Console.WriteLine($"数组arr[2]的值为: {arr[2]}");
   Console.ReadLine();
Copy after login

We return the reference type through ref, and then reassign the value in the arr array, correspondingly changed.

To summarize: the ref keyword has existed for a long time, but it can only be used for parameters. This time C#7.0 allows it not only to be passed as parameters, but also as local variables and return values. Okay

Okay, that’s all.

The above is the detailed content of Detailed explanation of ref locals and returns in C# 7.0. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template