在 c # 中,数组或列表是默认通过引用传递的吗?

是吗? 或者为了加快我的程序,我应该通过引用来传递它们吗?

57710 次浏览

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.

They are passed by value (as are all parameters that are neither ref nor out), but the value is a reference to the object, so they are effectively passed by reference.

The reference is 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 contents of the array will be seen by the caller, but reassigning the array won't:

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 reference is passed by reference - and the caller would see either change above.

(1) No one explicitly answered the OP's question, so here goes:

  • No. Explicitly passing the array or list as a reference will not affect performance.
  • What the OP feared might be happening is avoided because the function is already operating on a reference (which was passed by value). The top answer nicely explains what this means, giving an Ikea way to answer the original question.

(2) Good advice for everyone:

  • Read Eric Lippert's advice on when/how to approach optimization. Premature optimization is the root of much evil.

(3) Important, not already mentioned:

  • Use cases that require passing anything - values or references - by reference are rare.
  • Doing so gives you extra ways to shoot yourself in the foot, which is why C# makes you use the "ref" keyword on the method call as well. Older (pre-Java) languages only made you indicate pass-by-reference on the method declaration. And this invited no end of problems. Java touts the fact that it doesn't let you do it at all.