自修改对象的 Ref 与 No Ref
如果在函数中修改作为参数引用的对象,是否使用 ref 有关系吗?下面两个函数有区别吗?
void DisposeObject(ClassThing c)
{
c.Dispose();
}
void DisposeObject(ref ClassThing c)
{
c.Dispose();
}
If the object being referenced as a parameter is being modified in a function, does it matter if you use ref or not? Is there a difference between the following two functions?
void DisposeObject(ClassThing c)
{
c.Dispose();
}
void DisposeObject(ref ClassThing c)
{
c.Dispose();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没关系。重要的是,如果您要向
c
分配某些内容(并希望它反映在方法之外):在这种情况下,您将使用
参考
。It doesn't matter. What matters is if you're assigning something to
c
(and want it reflected outside the method):In that case you'd use
ref
.这并不取决于你的情况。
但是:
如果您使用 ref 关键字传递引用对象,则可以在方法内部更改引用以指向此类型的另一个对象(因此它将在方法外部可见)
It doesnt depend in your case.
BUT:
if you pass a reference object with the ref keyword you have inside of the method the possibility to change the reference to point to another Object of this type (so it will be visible outside of the method)
根据传递引用类型参数的 MSDN 指南:
因此,您可以更改原始对象,但无法更改原始对象以引用内存中的不同位置。示例:
所以差异确实很重要,尽管我不具体了解
Dispose()
的行为。According to the MSDN guide to passing reference-type parameters:
So you can alter the original object, but you cannot change the original object to reference a different location in memory. Example:
So the difference does matter, although I don't know specifically about the behavior of
Dispose()
.