简体   繁体   中英

Static class/method this and generics

So I have a certain method I want to call on a List (it's a generic method that I run every time in different files, so I would like to put it in a static class).

The method is this:

public static List<Item> GetRangeOrMax(this List<Item> list, int amount)
        {
            return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);
        }

The problem is that not every list I need to run this on is of the type Item. I was wondering if I would be able to solve this using generics? Say something along the lines of (this List<T> list ...

The problem here being that the method must also return that value and I would like to keep using the this keyword. If not possible I guess I'll have to make the method with a different overloader for each type.

You can use a generic extension method.

static List<T> GetRangeOrMax<T>(this List<T> list, int amount)        
{            
      return list.Count < amount ? list.GetRange(0, list.Count) : list.GetRange(0, amount);        
}

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