【问题标题】:Get value from table as a reference从表中获取值作为参考
【发布时间】:2017-09-01 12:34:49
【问题描述】:

在 c++ 中,可以通过引用 (&) 或指针 (*) 来实现。在 C# 中有“ref”。如何从表中获取值并通过引用对其进行更改?

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# 不是 C++。没有规则说它存在于 C++ 中就必须存在于 C# 中。

标签: c# visual-studio reference ref


【解决方案1】:

在不安全模式下可以带指针

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

【讨论】:

    【解决方案2】:

    没有。像 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 中是可能的。

    【讨论】:

      【解决方案3】:

      这仅在 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 返回。我建议谨慎使用这两个功能 - 虽然它们肯定很有用,但许多 C# 开发人员并不熟悉它们,而且我可以看到它们引起了很大的混乱。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 2020-08-11
        • 2018-12-06
        相关资源
        最近更新 更多