为什么 C# 不允许将 using 变量作为 ref 或 out 传递给函数
为什么 C# 不允许将变量作为 ref 或 out 从 using 块传递到函数?
这是我的代码:
using (Form s = new Form())
{
doSomthing(ref s);
}
函数在 using 块结束之前结束,为什么 C# 不让我将 s
作为 ref 或 out 参数传递?
Possible Duplicate:
Passing an IDisposable object by reference causes an error?
Why doesn't C# allow passing a variable from a using block to a function as ref or out?
This is my code:
using (Form s = new Form())
{
doSomthing(ref s);
}
The function ends before the using block ends, why doesn't C# let me pass s
as ref or out parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
using
变量被视为只读,因为任何重新分配都可能是错误。由于 ref 允许重新分配,这也是一个问题。在 IL 级别,out
与ref
几乎相同。但是,我怀疑您需要此处
ref
;您已经将引用传递给表单,因为它是一个类。对于引用类型,ref
的主要目的是允许您重新分配变量,并让调用者看到重新分配,即,如果您只是与表单对象对话,则不需要:
因为它是相同的表单对象 。
using
variables are treated as readonly, as any reassignment is probably an error. Sinceref
allows reassignment, this would also be an issue. At the IL level,out
is pretty-much identical toref
.However, I doubt you need
ref
here; you are already passing a reference to the form, since it is a class. For reference-types, the main purpose of aref
would be to allow you to reassign the variable, and have the caller see the reassignment, i.e.it is not required if you are just talking to the form object:
since it is the same form object.
using()
语句中的 var 在块内被视为只读。请参阅§ 8.13:但请注意,这仅适用于声明为 using 语句一部分的变量,以下内容是合法的(只是不是一个好主意):
The var in a
using()
statement is considered read-only inside the block. See § 8.13:But note that this only applies to variables declared as part of the using statement, the following is legal (just not a good idea):
原因之一可能是
doSomthing
可能使s
引用另一个Form
实例,而不是我们创建的实例。这可能会导致资源泄漏,因为 using 块随后会在来自该方法的Form
实例上调用Dispose
,而不是在 using 块中创建的实例。One reason could be that
doSomthing
could makes
refer to anotherForm
instance than the one we have created. That could introduce a resource leak since the using block would then invokeDispose
on theForm
instance that came from the method, and not the one created in the using block.