2017-04-26 65 views
3

为什么有以下代码编译时从Idisposable实现泛型类时的不同行为?

public class Repository<T> : IRepository<T> where T : BaseEntity, IDisposable 

而且

public class Repository<T> : IDisposable, IRepository<T> where T : BaseEntity 

的行为改变的情况下,如果我离开的实现类空,在上述情况下,不希望我实现Dispose( ) 方法。但是,在下面需要实现Dispose()方法。 下面是完整的测试代码:

public interface Itest<T> where T: testA{ } 
public class testA { } 
public class test2<T> : Itest<T> where T : testA,IDisposable{ } //successfully compiled 
public class test3<T> : IDisposable, Itest<T> where T : testA { }//Failed compiled : need to implement Dispose() 

回答

3

当你有

public class Repository<T> : IRepository<T> where T : BaseEntity, IDisposable 

然后T必须实现IDisposable

当你有

public class Repository<T> : IDisposable, IRepository<T> where T : BaseEntity 

然后Repository必须实现IDisposable

当你想创建的test2<T>一个实例,你应该提供由testA派生并实现IDisposable一个泛型参数。

+0

我没有在BaseEntity中提供IDisposable的实现,为什么仍然编译成功。它应该要求我在BaseEntity类中提供Dispose()方法,但它的编译很愉快。 –

+1

当你想创建'test2 '的实例时,你应该提供一个从'testA'派生并实现'IDisposable'的通用参数。 @NomiAli – dotctor

1

在第一个代码示例中,T必须实现IDisposable。在第二个代码示例中,Repository本身必须实现IDisposable