起初我有一些这样的代码:
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.
关于c# - C# using 语句需要赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747051/