2010-06-03 23 views
2

我试图在using语句中使用泛型类,但编译器似乎无法将其视为实现IDisposable。在使用语句中不能使用通用C#类

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Objects; 

namespace Sandbox 
{ 
    public sealed class UnitOfWorkScope<T> where T : ObjectContext, IDisposable, new() 
    { 
     public void Dispose() 
     { 
     } 
    } 

    public class MyObjectContext : ObjectContext, IDisposable 
    { 
     public MyObjectContext() : base("DummyConnectionString") { } 

     #region IDisposable Members 

     void IDisposable.Dispose() 
     { 
      throw new NotImplementedException(); 
     } 

     #endregion 
    } 

    public class Consumer 
    { 
     public void DoSomething() 
     { 
      using (new UnitOfWorkScope<MyObjectContext>()) 
      { 
      } 
     } 
    } 
} 

编译器错误是:

Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable' 

我实现了IDisposable上UnitOfWorkScope(并看看是否这就是问题所在,也MyObjectContext)。

我错过了什么?

回答

13

我实现了IDisposable上UnitOfWorkScope

不,你没有。你指定你的T应该实现IDisposable。

使用此语法:

public sealed class UnitOfWorkScope<T> : IDisposable where T : ObjectContext, IDisposable, new() 

因此,首先声明一下类/接口UnitOfWorkScope器械(IDisposable接口),然后宣布T的约束(T必须从ObjectContext的派生,实现IDisposable,有一个参数的构造函数)

+0

+1 - 确切地说。 UnitOfWorkScope不在给定的源中实现IDisposable。 – TomTom 2010-06-03 05:48:23

5

你指定在UnitOfWorkScope<T>T必须实现IDisposable,但不是说UnitOfWorkScope<T>本身实现IDisposable。我想你想要这样的:

public sealed class UnitOfWorkScope<T> : IDisposable 
    where T : ObjectContext, IDisposable, new() 
{ 
    public void Dispose() 
    { 
     // I assume you'll want to call IDisposable on your T here... 
    } 
} 
4

你已经实现了IDisposable的一切,除了你需要实现它是什么:UnitOfWorkScope<T>实现Dispose方法,但绝不实现IDisposable。 where子句适用于T,不适用于班级。