編譯器警告 (層級 2) CS0728
更新:2007 年 11 月
錯誤訊息
可能對 using 或 lock 陳述式的引數 (區域 'variable') 進行不正確的指派。這個區域的原始值將會發生 Dispose 呼叫或解除鎖定。
using 或 lock 區塊造成暫時資源流失的情況有好幾種。以下即為一例:
thisType f = null;
using (f)
{
f = new thisType();
...
}
在以上的範例中,當 using 區塊完成執行時,thisType 變數的原始值 (如 null 等) 將被處置,但在這個區塊內所建立的 thisType 物件雖然終究會被記憶體回收,但不會立即被處置。
若要解決這個錯誤,請使用下列格式:
using (thisType f = new thisType())
{
...
}
在上面的情況中,新配置的 thisType 物件就會被處置。
範例
下列程式碼會產生警告 CS0728。
// CS0728.cs
using System;
public class ValidBase : IDisposable
{
public void Dispose() { }
}
public class Logger
{
public static void dummy()
{
ValidBase vb = null;
using (vb)
{
vb = null; // CS0728
}
vb = null;
}
public static void Main() { }
}