c# 中是否默认通过引用传递数组或列表? [英] Are arrays or lists passed by default by reference in c#?

查看:22
本文介绍了c# 中是否默认通过引用传递数组或列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Do they? Or to speed up my program should I pass them by reference?

推荐答案

引用 按值传递.

.NET 中的数组是堆上的对象,因此您有一个引用.该引用是按值传递的,这意味着调用者会看到对数组内容的更改,但重新分配数组不会:

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
}

如果您添加 ref 修饰符,引用 将通过引用传递 - 调用者将看到上述任一更改.

If you add the ref modifier, the reference is passed by reference - and the caller would see either change above.

这篇关于c# 中是否默认通过引用传递数组或列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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