为什么裁判被用于在C#中数组参数? [英] Why would ref be used for array parameters in C#?

查看:105
本文介绍了为什么裁判被用于在C#中数组参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读网页的 传递数组使用ref和out(C#编程指南) 的,并想知道为什么我们需要定义数组参数作为ref参数时,它已经是一个引用类型。不会在被调用函数的变化在调用函数中反映出来?


解决方案

会不会在被调用函数的变化在调用函数中反映出来?




更改到的内容的数组的会反映在呼叫者方法 - 但改变的参数本身的不会。因此,例如:

 公共无效美孚(INT []×)
{
//的影响这条线的是给呼叫者
X可见[0] = 10;

//这一行是没有意义的
X = INT新[] {20};
}
...
INT [] =原新INT [10];
美孚(原件);
Console.WriteLine(原[0]); //输出10

如果我们改变了

现在有一个签名:

 公共无效美孚(参考INT []×)

和改变调用代码为:

 美孚(REF原件); 



然后将打印20。



要了解一个变量,它的值是指物体之间的差别是非常重要的 - 同样地修改之间的对象的和修改的变量

$ b。
$ b

查看参数我文章在C#为传递更多信息。


I read the page Passing Arrays Using ref and out (C# Programming Guide) and was wondering why we would need to define an array parameter as a ref parameter when it is already a reference type. Won't changes in the callee function be reflected in the caller function?

解决方案

Won't changes in the callee function be reflected in the caller function?

Changes to the contents of the array would be reflected in the caller method - but changes to the parameter itself wouldn't be. So for example:

public void Foo(int[] x)
{
    // The effect of this line is visible to the caller
    x[0] = 10;

    // This line is pointless
    x = new int[] { 20 };
}
...
int[] original = new int[10];
Foo(original);
Console.WriteLine(original[0]); // Prints 10

Now if we changed Foo to have a signature of:

public void Foo(ref int[] x)

and changed the calling code to:

Foo(ref original);

then it would print 20.

It's very important to understand the difference between a variable and the object that its value refers to - and likewise between modifying an object and modifying a variable.

See my article on parameter passing in C# for more information.

这篇关于为什么裁判被用于在C#中数组参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆