c# using 语句是否需要赋值?
Does c# using statement need assignment?
起初我有这样的代码:
WindowsIdentity otherIdentity = // got that from somewhere else
WindowsImpersonationContext context = otherIdentity.Impersonate();
Ldap.DoStuff();
context.Undo();
context.Dispose();
知道 WindowsImpersonationContext
实现 IDisposable
并且 Dispose()
也调用 Undo()
,我想我应该改用 using
:
using (var context = otherIdentity.Impersonate())
{
// Run as other user
Ldap.DoStuff();
}
现在,ReSharper 正确地注意到我没有使用 context
并建议删除分配。这也有效吗?它在编译时扩展到什么代码?
using (otherIdentity.Impersonate())
{
Ldap.DoStuff();
}
是的,你可以在using
语句中省略变量,编译器会自动引入一个隐藏变量,就好像你写了
using (var temp = otherIdentity.Impersonate())
{
Ldap.DoStuff();
}
除了您不能在 using
语句的正文中访问 temp
。
奇怪的是,MSDN Library 中似乎没有记录此语法。相反,请参考 C# 规范:
A using statement of the form
using (ResourceType resource = expression) statement
corresponds to one of three possible expansions.
[...]
A using
statement of the form
using (expression) statement
has the same three possible expansions. In this case ResourceType
is implicitly the compile-time type of the expression
, if it has one. Otherwise the interface IDisposable
itself is used as the ResourceType
. The resource
variable is inaccessible in, and invisible to, the embedded statement.
起初我有这样的代码:
WindowsIdentity otherIdentity = // got that from somewhere else
WindowsImpersonationContext context = otherIdentity.Impersonate();
Ldap.DoStuff();
context.Undo();
context.Dispose();
知道 WindowsImpersonationContext
实现 IDisposable
并且 Dispose()
也调用 Undo()
,我想我应该改用 using
:
using (var context = otherIdentity.Impersonate())
{
// Run as other user
Ldap.DoStuff();
}
现在,ReSharper 正确地注意到我没有使用 context
并建议删除分配。这也有效吗?它在编译时扩展到什么代码?
using (otherIdentity.Impersonate())
{
Ldap.DoStuff();
}
是的,你可以在using
语句中省略变量,编译器会自动引入一个隐藏变量,就好像你写了
using (var temp = otherIdentity.Impersonate())
{
Ldap.DoStuff();
}
除了您不能在 using
语句的正文中访问 temp
。
奇怪的是,MSDN Library 中似乎没有记录此语法。相反,请参考 C# 规范:
A using statement of the form
using (ResourceType resource = expression) statement
corresponds to one of three possible expansions.
[...]
A
using
statement of the formusing (expression) statement
has the same three possible expansions. In this case
ResourceType
is implicitly the compile-time type of theexpression
, if it has one. Otherwise the interfaceIDisposable
itself is used as theResourceType
. Theresource
variable is inaccessible in, and invisible to, the embedded statement.