[英]Passing with ref keyword
我在主表单中有2个标签页(tabA和tabB)。 说我通过tabA
到tabB
的主要形式initalization:
tabB = new TabB(tabA);
因此,我观察到的是,在更改tabA
(例如tabA.Text
)内的值之后, tabB
( tabB.tabA.Text
)内的值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
和基元)相反。
区别在于,通过使用ref
关键字,您可以更改引用本身,而不仅仅是引用所指向的对象。
void funcA(TabA tabA)
{
// setting tabA to null here has no effect outside this function
tabA = null;
}
void funcB(ref TabA tabA)
{
// setting tabA to null persists outside this function
// and changes the actual reference passed in.
tabA = null;
}
// tabA initialized to non-null
tabA = new TabA();
funcA(tabA);
// tabA is still not null
funcB(ref tabA);
// tabA is now null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.