繁体   English   中英

通过ref关键字传递

[英]Passing with ref keyword

我在主表单中有2个标签页(tabA和tabB)。 说我通过tabAtabB的主要形式initalization:

tabB = new TabB(tabA);

因此,我观察到的是,在更改tabA (例如tabA.Text )内的值之后, tabBtabB.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和基元)相反。

所不同的是,如果你改变了对象指向 tabA的说法TabB构造, tabA将使用新的对象了。

实际上,没有办法传递对象本身,但是您可以进行复制/克隆,看起来就像原始对象一样。 对于复制Windows控件的一般情况,已经编写了一个很好的答案 ,而对于选项卡仅给出了答案

区别在于,通过使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM