有什么用&QUOT的;参考"在C#中引用类型变量? [英] What is the use of "ref" for reference-type variables in C#?
问题描述
我明白,如果我传递一个值类型( INT
,结构
等)作为参数(不包括 REF
关键字),该变量的副本传递到方法,但如果我使用 REF
关键字该变量的引用传递,而不是一个新的。
但随着引用类型,如类,即使没有 REF
关键字的引用传递给方法,而不是一个副本。那么,什么是使用 REF参考类型
关键字?
举个例子:
变种x =新的Foo();
什么是以下区别?
空白栏(美孚Y){
y.Name =2;
}
和
无效吧(参考美孚Y){
y.Name =2;
}
您可以改变什么富
点,使用是
:
富富=新的Foo(1);酒吧无效(参考美孚Y)
{
Y =新的Foo(2);
}酒吧(REF富);
// foo.Name ==2
I understand that if I pass a value-type (int
, struct
, etc.) as a parameter (without the ref
keyword), a copy of that variable is passed to the method, but if I use the ref
keyword a reference to that variable is passed, not a new one.
But with reference-types, like classes, even without the ref
keyword, a reference is passed to the method, not a copy. So what is the use of the ref
keyword with reference-types?
Take for example:
var x = new Foo();
What is the difference between the following?
void Bar(Foo y) {
y.Name = "2";
}
and
void Bar(ref Foo y) {
y.Name = "2";
}
You can change what foo
points to using y
:
Foo foo = new Foo("1");
void Bar(ref Foo y)
{
y = new Foo("2");
}
Bar(ref foo);
// foo.Name == "2"
这篇关于有什么用&QUOT的;参考"在C#中引用类型变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!