在使用Statement中不能使用Generic C#Class

Eri*_* J. 2 c# generics idisposable

我试图在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>())
            {
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器错误是:

Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?

Mic*_*tum 13

我在UnitOfWorkScope上实现了IDisposable

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

使用以下语法:

public sealed class UnitOfWorkScope<T> : IDisposable where T : ObjectContext, IDisposable, new()
Run Code Online (Sandbox Code Playgroud)

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


Dea*_*ing 5

您已指定Tin UnitOfWorkScope<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...
    }
}
Run Code Online (Sandbox Code Playgroud)