简体   繁体   中英

Generic constrain for Lists and Collections

I have a Generic method which looks something like this:

public int GetCount<T>(T collection) where T: ICollection
{
   return collection.Count;    
}

Now I want to be able to call this method where the collection parameter can be a List<T> or a HashSet<T> . The current code doesn't fulfill that since the parameters I want to pass do not inherit the ICollection interface. Now would there be any way I could achieve that with a simple constrain?

Why don't:

public int GetCount<T>(ICollection<T> collection)
{
   return collection.Count;    
}

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