C# 引用手册将using 语句的语法定义为:
using-statement:
using ( resource-acquisition ) embedded-statement
resource-acquisition:
local-variable-declaration
expression
谁能给我提供一个在using 语句中使用表达式的例子。 常规示例使用变量声明。
最佳答案
使用表达式的例子如下:
var stream = new MemoryStream();
using(stream)
{
//Perform operations with stream here.
}
//Stream is now disposed.
这里,stream
变量在 using 之外声明,但被 using 包装。然后它将在完成后处理 stream
变量。
这不是一个很常见的模式,但它对于处理资源后可能需要对其执行其他操作的地方很有用。
这可以与方法调用等一起使用。基本上可以使用任何求值为 IDisposable
类型的表达式。通常,无法访问 using 语句中的 IDisposable
没有多大用处。
我看到它以这种方式使用的唯一场景是在 ASP.NET MVC 中使用表单助手,例如。
@using(Html.BeginForm())
{
@Html.TextBox("Name");
}
关于c# - C# using 语句中的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171464/