简体   繁体   中英

Implementing generic class and multiple interfaces

I have the following class definition:

public class SessionTreeManager<T> 
    : DataManager<T> where T : DataItem, IDeletable, IAnotherInterface

I only want T to be a DataItem and to implement the other two interfaces. The compiler seems to think I want T to be any of the 3 and gives build errors as my T in the class above doesn't implement all 3 and this class cant find methods to override.

Is this possible?

If I understand your question correctly, you have to do the following:

public class SessionTreeManager<T> 
    : DataManager<T>, IDeletable, IAnotherInterface 
    where T : DataItem {}

Which says, SessionTreeManager extends/implements DataManager , IDeletable and IAnotherInterface and the generic is constrained to DataItem .

You can also set the extends to DataManager<DataItem> as mentioned in the other comment, but then the parent methods will not be constrained to class T and will rather be constrained to its parent DataItem . This way all the methods of SessionTreeManager as well as its parent class DataManager will be constrained to the subclass of DataItem which is class T

尝试这个

public class SessionTreeManager<T> : DataManager<DataItem>, IDeletable, IAnotherInterface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM