使用IDisposable进行接口继承?

时间:2012-05-22 15:17:57

标签: c# inheritance

我有以下继承层次结构:

public interface IRepository<T> : IDisposable
{
    void Add(T model);
    void Update(T model);

    int GetCount();

    T GetById(int id);
    ICollection<T> GetAll();
}

public interface IAddressRepository : IRepository<Address>
{
}

这段代码:

var adrs = new Address[]{
    new Address{Name="Office"}
};

using (IAddressRepository adrr = new AddressRepository())
    foreach (var a in adrs)
        adrr.Add(a);

但是,此代码无法编译。它给了我这个错误信息:

Error   43  
'Interfaces.IAddressRepository': type used in a using statement must be
 implicitly convertible to 'System.IDisposable'

但是,IAddressRepository的父级继承自IDisposable

这里发生了什么?如何编译代码?

2 个答案:

答案 0 :(得分:7)

我的猜测是你犯了一个错误 - 要么你没有重新编译包含IRepository<T>接口的程序集,因为它是从IDisposable继承的,或者你引用了错误的副本,或者你引用了其他一些IAddressRepository

尝试执行Clean,然后执行Rebuild All,并检查引用的路径。如果项目在同一解决方案中,请确保引用包含IRepository<T> / IAddressRepository而不是DLL的项目。

还要确保AddressRepository 实际实现 IAddressRepository。它可能只是报告错误的错误。

编辑:所以分辨率似乎是包含AddressRepository父类的程序集没有编译。这导致调试器抱怨AddressRepository没有实现IDisposable,而不是(更明智的)“由于其保护级别而无法访问”错误编译类本身。我的猜测是你也有这个错误,但是先解决这个错误。

答案 1 :(得分:2)

适合我:

using System;

public class Address {}

public interface IRepository<T> : IDisposable
{
    void Add(T model);
    void Update(T model);
}

public interface IAddressRepository : IRepository<Address>
{
}

class Program
{
    public static void Main()
    {
        using (var repo = GetRepository())
        {
        }
    }

    private static IAddressRepository GetRepository()
    {
        // TODO: Implement :)
        return null;
    }
}

我怀疑你可能有两个IAddressRepository接口。您确定Interfaces.IAddressRepository延伸IRepository<T>,并且延伸IDisposable吗?