繁体   English   中英

在C#大括号中按值传递和按引用传递

[英]Pass by value and pass by reference in C# curly bracket

为什么每次运行程序时都保持“}期望”? 我认为我没有错过任何花括号。 可能还有其他吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] anArray = new int[] {30, 40, 60, 70, 80, 90, 100, 110};

            var byVal = anArray[0];
            Console.WriteLine("by value: " + byVal);

            ref int byRef = anArray[0];
            Console.WriteLine("by reference: " + byRef);


       }
    }
}

在此处输入图片说明

它无法解析您的代码(不确定为什么要在} )。

这是无效的C#代码

ref int byRef = anArray[0];

您不能将变量定义为ref 在将参数传递给方法时使用它。 例如:

void Main()
{
    int b = 6;
    ChangeIt(ref b);
    Console.WriteLine(b);
}

void ChangeIt(ref int a)
{
    a = 5;
}

将打印出来5

您似乎误解了ref关键字的含义:它用于按引用传递参数,而不是对局部变量进行引用。

C#根据该变量的类型确定将变量作为引用或值:原始类型和struct是值类型,因此与这些类型相对应的变量存储值。 另一方面,类是引用类型,因此相应类型的变量存储引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM