“参考”关键字和引用类型
我团队中的某人偶然发现了引用类型上 ref 关键字的特殊用法,
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
有什么理由让理智的人会做这样的事情吗?我在 C# 中找不到这个用途
someone in my team stumbled upon a peculiar use of the ref keyword on a reference type
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
Is there any reason someone sane would do such a thing? I can't find a use for this in C#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
仅当他们想要将作为
myObject
传入的对象的引用更改为其他对象时。这很可能不是他们想要做的,并且不需要
ref
。Only if they want to change the reference to the object passed in as
myObject
to a different one.Chances are this is not what they want to do and
ref
is not needed.让
那么
但是如果就
那么
Let
then
But if just
then
如果该方法应该更改存储在传递给该方法的变量中的引用,则
ref
关键字非常有用。如果不使用ref
,则无法更改引用,只能更改对象本身在方法外部可见。The
ref
keyword is usefull if the method is supposed to change the reference stored in the variable passed to the method. If you do not useref
you can not change the reference only changes the object itself will be visible outside the method.这并没有什么奇怪的。如果您想要从方法返回多个值或者只是不想将返回值重新分配给作为参数传入的对象,则可以引用变量。
像这样:
而不是:
或者如果您想检索多个值:
There's nothing peculiar with this. You reference variables if you want to return several values from a method or just don't want to reassign the return value to the object you've passed in as an argument.
Like this:
instead of:
Or if you want to retrieve several values: