我在主窗体中有 2 个标签页(tabA 和 tabB)。假设我在主窗体初始化时将 tabA
传递给 tabB
:
tabB = new TabB(tabA);
所以我观察到的是,在更改 tabA
中的值(比如 tabA.Text
)之后,tabB
中的值(tabB.tabA.Text
) 也发生变化。
所以我的理解(来自 C++)是这类似于按引用传递。所以我的问题是,如果我改写这个有什么区别?
tabB = new TabB(ref tabA);
最佳答案
您对 C++ 的类比是不正确的。在 C# 中传递引用对象* 类似于在 C++ 中通过指针传递对象,除了 C# 不需要星号来取消引用这些指针。
在 C# 中通过引用传递类似于在 C++ 中通过引用传递指针:除了在函数中使用该指针之外,您还可以为其分配一个新值,从而更改指针的值在调用者中。
这是一个简短的例子:
void One(List<int> list) {
// Reassignment of the list is local to method One
list = new List<int> {1, 2, 3};
}
void Two(ref List<int> list) {
// Reassignment of the list is visible in the caller
list = new List<int> {1, 2, 3};
}
...
var demo = new List<int> {5, 6, 7};
One(demo);
// Here the list remains [5, 6, 7]
Two(ref demo);
// Here the list becomes [1, 2, 3]
* 与被复制的值对象相反,例如 struct
和原语。
关于c# - 使用 ref 关键字传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30545180/