c# - 从表中获取值作为引用

标签 c# visual-studio reference ref

在 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# 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# 开发人员并不熟悉它们,而且我认为它们会造成严重的混淆。

关于c# - 从表中获取值作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255859/

相关文章:

c# - 如何使用 slider 调整图像的亮度和对比度?

c# - 是否可以通过编程方式扩展 Azure 应用服务

c# - 重命名项目路径后如何将现有项目添加到 Visual Studio 2012

asp.net-mvc - IIS Express——让 SSL 工作

c++ - 使用函数引用

c++ - 在这个 C++ 函数中更新 Fortran 中的两个数组

c# - 旋转渐变在 WPF 中脱离 Canvas

具有重载的 C# 自定义事件

visual-studio - 适用于 Visual Studio 2010 编程的 PC

android - 如何在 Android 中引用其他应用程序的 R.java,如 com.android.music?