c# - C# using 语句需要赋值吗?

标签 c# using-statement

起初我有一些这样的代码:

WindowsIdentity otherIdentity = // got that from somewhere else
WindowsImpersonationContext context = otherIdentity.Impersonate();
Ldap.DoStuff();
context.Undo();
context.Dispose();

知道WindowsImpersonationContext实现IDisposableDispose()还可以调用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.

关于c# - C# using 语句需要赋值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41747051/

相关文章:

c# - ThreadPool.SetMinThreads() completionPortThreads 数量可以设置为0吗?

c# - NPOI 2.1.3.1 生成损坏的 XLSX 文件

c# using 语句放置

c++ - 在我的命名空间中公开外部库类时使用 typedef 或 using 关键字

c# - Magento Web 服务错误

c# - 使用 avimanager 从图像生成视频会引发错误

c# - 为什么我的动态值字典迭代(并行)丢弃了我的本地范围变量?

.net - 什么是托管 C++ 等效于 C# using 语句

C#: "Using"带有 HttpWebRequests/HttpWebResponses 的语句