Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#中传递数组参数:为什么它是通过引用隐式传递的?_C#_Arrays_Pass By Reference_Parameter Passing_Pass By Value - Fatal编程技术网

在C#中传递数组参数:为什么它是通过引用隐式传递的?

在C#中传递数组参数:为什么它是通过引用隐式传递的?,c#,arrays,pass-by-reference,parameter-passing,pass-by-value,C#,Arrays,Pass By Reference,Parameter Passing,Pass By Value,假设以下代码没有任何ref关键字,显然不会替换传递的变量,因为它是作为值传递的 class ProgramInt { public static void Test(int i) // Pass by Value { i = 2; // Working on copy. } static void Main(string[] args) { int i = 1; ProgramInt.Test(i);

假设以下代码没有任何
ref
关键字,显然不会替换传递的变量,因为它是作为值传递的

class ProgramInt
{
    public static void Test(int i) // Pass by Value
    {
        i = 2; // Working on copy.
    }

    static void Main(string[] args)
    {
        int i = 1;
        ProgramInt.Test(i);
        Console.WriteLine(i);
        Console.Read();

        // Output: 1
    }
}
现在要使该函数按预期工作,可以像往常一样添加
ref
关键字:

class ProgramIntRef
{
    public static void Test(ref int i) // Pass by Reference
    {
        i = 2; // Working on reference.
    }

    static void Main(string[] args)
    {
        int i = 1;
        ProgramInt.Test(ref i);
        Console.WriteLine(i);
        Console.Read();

        // Output: 2
    }
}
现在我不明白为什么传入函数时数组成员是通过引用隐式传递的。数组不是值类型吗

class ProgramIntArray
{
    public static void Test(int[] ia) // Pass by Value
    {
        ia[0] = 2; // Working as reference?
    }

    static void Main(string[] args)
    {
        int[] test = new int[] { 1 };
        ProgramIntArray.Test(test);
        Console.WriteLine(test[0]);
        Console.Read();

        // Output: 2
    }
}

你能想象通过值传递一个200万元素的数组吗?现在假设元素类型是
decimal
。您必须复制大约240MB 30.5175781MB的数据。

不,数组是类,这意味着它们是引用类型

如所示,数组是对象(System.Array是所有数组的抽象基类型),对象是通过引用传递的。

数组不是通过引用传递的。对数组的引用按值传递。如果需要更改传入数组变量指向的数组(例如更改数组的大小),则必须通过引用传递变量。

除了基本数据类型之外,您不能将任何其他内容作为传递值传递,数组是基本数据类型的集合,还允许在集合上传递值,这将创建集合的多个副本,这将影响性能

记住这一点的好方法是:

  • “ref”是变量的别名
  • 数组是变量的集合;每个元素都是一个变量
正常传递数组时,传递的是一组变量。集合中的变量不会更改

当您传递带有“ref”的数组时,您将为包含该数组的变量指定一个新名称

传递数组元素时,通常是在传递变量中的值

当您传递带有“ref”的数组元素(变量)时,您为该变量指定了一个新名称


有意义吗?

通常,您可以按任意类型的F12键来查找。如果声明说“class”,那么它是一个引用类型;如果它说“struct”,它就是一个值类型。不幸的是,它不允许您对数组执行此操作,这是一个遗憾。所以你只需要记住数组是引用类型,即使它是一个值类型的数组。为了补充Timwi所说的,F12是Visual Studio的热键。我要提到
System.array
,但我记得
System.ValueType
System.Enum
也是引用类型,然而,从逻辑上派生的值类型和枚举不是。结构不是“基本数据类型”,它们是按值传递的。我个人喜欢上面提到的地址,但大多数人仍然不明白这一点。这里有一种我用狗来比喻的方式,但它似乎真的很蹩脚:就我个人而言,我不喜欢“给一个新名字”的措辞。不知什么原因,我就是不明白。但我不知道新手会怎么看。