C#参考手册将使用语句的语法定义为:
using-statement:
using ( resource-acquisition ) embedded-statement
resource-acquisition:
local-variable-declaration
expression
有人可以为我提供一个使用使用语句内部表达式的示例。 传统的例子是使用变量声明。
答案 0 :(得分:3)
使用表达式的示例如下:
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");
}
答案 1 :(得分:1)
一个例子:
//Create the file.
using (FileStream fs = File.Create(path))
{
AddText(fs, "This is some text");
AddText(fs, "This is some more text,");
AddText(fs, "\r\nand this is on a new line");
AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");
for (int i=1;i < 120;i++)
{
AddText(fs, Convert.ToChar(i).ToString());
}
}
说明:
提供方便的语法,确保正确使用IDisposable对象。
using语句在块和块上的对象上调用Dispose方法。
即使抛出异常,它也会调用Dispose方法。
答案 2 :(得分:0)
要注意的关键事项实际上是第8.5.1节中local-variable-declaration
的定义
local-variable-declaration声明一个或 更多局部变量。local-variable-declaration:
local-variable-type 局部变量声明符local-variable-type:
类型
var局部变量声明符:
local-variable-declarator
local-variable-declarators,local-variable-declaratorlocal-variable-declarator:
标识符
identifier = local-variable-initializerlocal-variable-initializer:
表达阵列初始化
因此local-variable-declaration
可以表示为type identifer = expression
。那么using
的规范告诉你的是,您可以以var variableName = xxxxxxx
的形式声明变量,也可以单独使用xxxxxx
部分。
答案 3 :(得分:0)
我在这里没有提到的expression
的另一个例子是:
IDisposable disposable;
using (disposable = new SomeDisposableObject()) {
// do something
}
或
IDisposable disposable;
using (disposable = SomeExpressionOrFunctionThatEvaluatesToADisposable()) {
// do something
}
引用不必是IDisposable
类型,它可以是实现它的任何类型。