从table中获取值作为参考

Get value from table as a reference

在 C++ 中,可以通过引用 (&) 或指针 (*) 来完成。在 C# 中有 "ref"。如何从 table 获取值并通过引用更改它?

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] t=new int[3]{1,2,3};
            int a=t[0]; //ref int a=t[0];
            a+=10;
            System.Console.WriteLine("a={0}", a);   //11
            System.Console.WriteLine("t[0]={0}", t[0]); //1
        }
    }
}

例如在 C++ 中

int &a=tab[0];

这仅在 C# 7 中变得可行,使用 ref locals:

public class Program
{
    public static void Main(string[] args)
    {
        int[] t = {1, 2, 3};
        ref int a = ref t[0];
        a += 10;
        System.Console.WriteLine($"a={a}");       // 11
        System.Console.WriteLine($"t[0]={t[0]}"); // 11
    }
}

这是重要的一行:

ref int a = ref t[0];

C# 7 还支持 ref returns。我建议谨慎使用这两个功能 - 虽然它们肯定有用,但许多 C# 开发人员不熟悉它们,而且我可以看到它们会造成严重的混淆。

没有。像 int 这样的值类型是不可能的。但是,它是引用类型的标准。

例如:

class MyClass
{
    public int MyProperty {get; set;}
}

void Main()
{
    var t=new MyClass[3]{new MyClass {MyProperty=1},new MyClass {MyProperty=2},new MyClass {MyProperty=3}};
    var a=t[0]; //ref int a=t[0];
    a.MyProperty+= 10;
    System.Console.WriteLine("a={0}", a.MyProperty);   //11
    System.Console.WriteLine("t[0]={0}", t[0].MyProperty); //11
}

给出了预期的结果。

编辑:显然我落后了。正如 Jon Skeet 指出的那样,在 C# 7.0 中是可能的。

Unsafe模式下可以带指针

unsafe
{
      int[] t = new int[3] { 1, 2, 3 };
      fixed (int* lastPointOfArray = &t[2])
      {
          *lastPointOfArray = 6;
          Console.WriteLine("last item of array {0}", t[2]); // =>> last item of array 6
      }
}