Extension method for List AddToFront(T object) how to?

后端 未结 1 1256
生来不讨喜
生来不讨喜 2020-12-16 09:59

I want to write an extension method for the List class that takes an object and adds it to the front instead of the back. Extension methods really confuse me.

相关标签:
1条回答
  • 2020-12-16 10:22

    List<T> already has an Insert method that accepts the index you wish to insert the object. In this case, it is 0. Do you really intend to reinvent that wheel?

    If you did, you'd do it like this

    public static class MyExtensions 
    {
        public static void AddToFront<T>(this List<T> list, T item)
        {
             // omits validation, etc.
             list.Insert(0, item);
        }
    }
    
    // elsewhere
    
    List<int> list = new List<int>();
    list.Add(2);
    list.AddToFront(1);
    // list is now 1, 2
    

    But again, you're not gaining anything you do not already have.

    0 讨论(0)
提交回复
热议问题