c# 中默认通过引用传递数组或列表吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/967402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are arrays or lists passed by default by reference in c#?
提问by Jorge Branco
Do they? Or to speed up my program should I pass them by reference?
他们吗?或者为了加速我的程序,我应该通过引用传递它们吗?
回答by Paul Sonier
Yes, they are passed by reference by default in C#. All objects in C# are, except for value types. To be a little bit more precise, they're passed "by reference by value"; that is, the value of the variable that you see in your methods is a reference to the original object passed. This is a small semantic point, but one that can sometimes be important.
是的,它们在 C# 中默认通过引用传递。C# 中的所有对象都是,值类型除外。更准确地说,它们是“按值引用”传递的;也就是说,您在方法中看到的变量值是对传递的原始对象的引用。这是一个小的语义点,但有时可能很重要。
回答by plinth
They are passed by value (as are all parameters that are neither ref nor out), but the value isa reference to the object, so they are effectively passed by reference.
它们是按值传递的(就像所有既不是 ref 也不是 out 的参数一样),但值是对对象的引用,因此它们实际上是按引用传递的。
回答by Marc Gravell
The referenceis passed by value.
该参考被传递通过值。
Arrays in .NET are object on the heap, so you have a reference. That reference is passed by value, meaning that changes to the contentsof the array will be seen by the caller, but reassigningthe array won't:
.NET 中的数组是堆上的对象,因此您有一个引用。该引用是按值传递的,这意味着调用者将看到对数组内容的更改,但重新分配数组不会:
void Foo(int[] data) {
data[0] = 1; // caller sees this
}
void Bar(int[] data) {
data = new int[20]; // but not this
}
If you add the ref
modifier, the referenceis passed by reference- and the caller would see either change above.
如果添加ref
改性剂,将参考传递引用-和呼叫者会显示上述变化。