编译器警告(等级 2)CS0728
更新:2007 年 11 月
错误消息
对局部变量“variable”的赋值可能不正确,该变量是 using 或 lock 语句的参数。 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() { }
}