简体   繁体   中英

How do I create a generic class that takes as its generic type a generic class?

Basically, I want to write a wrapper for all ICollection<> types. Lets call it DelayedAddCollection. It should take any ICollection as its .

Furthermore, I need access to that ICollection type's generic type as the Add method needs to restrict its parameter to that type.

The syntax I would imagine would look something like this...

public DelayedAddConnection<T>: where T:ICollection<U> {
   ....

   public void Add(U element){
     ...
   }
}

What is the real correct syntax to do this?

You need to add another generic type parameter:

public class DelayedAddConnection<T, U> where T : ICollection<U>
{

}

So, for future reference the final, cleanest version of this idea I implemented thanks to all the suggestions and comments was this:

public class DelayedUpdateCollection<U>: ICollection<U> 
{

    ICollection<U> collection;


    public DelayedUpdateCollection(ICollection<U> coll){
        collection = coll;
    }

    ...

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