Compiler Error CS1674

“T”:using 语句中使用的类型必须可以隐式转换为“System.IDisposable”

using 语句 旨在用于确保在 using 块的最后处置对象,因此只有可处置的类型才能在这类语句中使用。例如,值类型不是可处置的,并且没有约束为类的类型参数不能假定为可处置。

下面的示例生成 CS1674。

// CS1674.cs
class C
{
   public static void Main()
   {
      int a = 0;
      a++;

      using (a) {}   // CS1674
   }
}

下面的示例生成 CS1674。

// CS1674_b.cs
using System;
class C {
   public void Test() {
      using (C c = new C()) {}   // CS1674
   }
}

// OK
class D : IDisposable {
   void IDisposable.Dispose() {}
   public void Dispose() {}

   public static void Main() {
      using (D d = new D()) {}
   }
}

下面的示例说明了需要使用一个类类型约束来确保未知的类型参数是可释放的。下面的示例生成 CS1674。

// CS1674_c.cs
// compile with: /target:library
using System;
public class C<T>
// Add a class type constraint that specifies a disposable class.
// Uncomment the following line to resolve.
// public class C<T> where T : IDisposable
{
   public void F(T t)
   {
      using (t) {}   // CS1674
   }
}