2017-04-26 38 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