如果我将对象传递给方法,为什么要使用 ref 关键字?这不是默认行为吗?
例如:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
输出是“Bar”,这意味着该对象作为引用传递。
Pass a ref
如果你想改变对象是什么:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef x)
{
x = new TestRef();
x.Something = "Not just a changed TestRef, but a completely different TestRef object";
}
调用 DoSomething 后,t
不参考原文new TestRef
,但指的是完全不同的对象。
如果您想更改不可变对象的值,例如,这也可能很有用。 Astring
。您无法更改 a 的值string
一旦它被创建。但是通过使用ref
,您可以创建一个函数来将字符串更改为另一个具有不同值的字符串。
使用这不是一个好主意ref
除非需要。使用ref
赋予方法自由地将参数更改为其他内容,方法的调用者将需要进行编码以确保他们处理这种可能性。
此外,当参数类型是对象时,对象变量始终充当对象的引用。这意味着当ref
使用关键字您已经获得了对参考的引用。这允许您执行上面给出的示例中描述的操作。但是,当参数类型是原始值时(例如int
),那么如果在方法内部赋值这个参数,方法返回后传入的参数值就会改变:
int v = 1;
Change(ref v);
Debug.Assert(v == 5);
WillNotChange(v);
Debug.Assert(v == 5); // Note: v doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)