using 语句对变量进行多次赋值

using statement for multiple assignments to the variable

我有一个 System.Drawing.Pen 类型的变量“pen”,它在特定方法中被多次赋值。我想把它放在“使用”声明中。我该怎么做?

Pen pen = new Pen(Color.Gray);
// some code which uses gray value
pen = new Pen(Color.Green);
// some code which uses green value
pen = new Pen(Color.Red);
// some code which uses red value

提前致谢。

好吧,Pen 实现了 IDisposable,因为它分配了 非托管资源 (HPEN),因此在一般情况下 using是必须的。 在您当前的代码中,您有 资源泄漏:

Pen pen = new Pen(Color.Gray);

// some code which uses gray value

pen = new Pen(Color.Green); // <- from now on Pen(Color.Gray) is leaked

// some code which uses green value
pen = new Pen(Color.Red);  // <- from now on Pen(Color.Green) is leaked
// some code which uses red value

您可以使用 预定义 笔(不需要 using):

Pen pen = Pens.Gray;

// some code which uses gray value

pen = Pens.Green;

// some code which uses green value

pen = Pens.Red;

// some code which uses red value

或者,如果您想手动创建 Pen,请将它们包装到 using:

using (Pen pen = new Pen(Color.Gray)) {
  // some code which uses gray value
}

using (Pen pen = new Pen(Color.Green) {
  // some code which uses green value
}

using (Pen pen = new Pen(Color.Red)) {
  // some code which uses red value
}