简体   繁体   中英

Iterating through list of interfaces

I've got an interface with type T objects like so

public interface IService<T>

I've got a bunch of these interfaces with all different type T's. How can I add these interfaces into a List of some sort, iterate through the list and call a common method used by the interface. Any ideas? Is there an alternative approach?

If I add it to a list, I just can't see a way of casting the type T correctly.

If the method is common, then presumably it doesn't depend on the T , so you should be able to do:

interface IService {
    void TheMethod();
}
interface IService<T> : IService {
    // other stuff
}

then have a List<IService> , and just:

foreach(var svc in list) svc.TheMethod();

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