代码之家  ›  专栏  ›  技术社区  ›  Eric J.

不能在using语句中使用泛型C类

  •  2
  • Eric J.  · 技术社区  · 16 年前

    我正在尝试在 using 语句,但编译器似乎无法将其视为实现IDisposable。

    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'
    

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

    我错过了什么?

    3 回复  |  直到 16 年前
        1
  •  13
  •   Michael Stum    16 年前

    我在UnitOfWorkScope上实现了IDisposable

    不,您没有。您指定了不应实现IDisposable。

    使用此语法:

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

    因此,首先声明工作范围实现的类/接口UnitOfWorkscope(IDisposable),然后声明T的约束(T必须从ObjectContext派生,实现IDisposable并具有无参数构造函数)

        2
  •  5
  •   Dean Harding    16 年前

    您已指定 T 在里面 UnitOfWorkScope<T> 必须实施 IDisposable ,但不是那样 UnitOfWorkscope<t> 它本身 器具 不可分的 . 我想你想要这个:

    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...
        }
    }
    
        3
  •  4
  •   Eric Lippert    16 年前

    您已经实现了IDisposable,但需要在以下位置实现它: UnitOfWorkScope<T> 实现Dispose方法,但 从不实现IDisposable . WHERE条款适用于 T 不是给全班的。

    推荐文章