T>的名单,LT扩展方法; AddToFront(T对象)怎么样? [英] Extension method for List<T> AddToFront(T object) how to?

查看:134
本文介绍了T>的名单,LT扩展方法; AddToFront(T对象)怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要写的列表这需要一个对象,并将其添加到前面而不是后面的类的扩展方法。扩展方法真的让我困惑。有人可以帮我这个

  myList.AddToFront(T对象)?; 


解决方案

列表< T> 已经接受要插入对象的索引的插入方法。在这种情况下,它是0。你真的打算彻底改造该车轮?



如果你这样做,你会做这样

 公共静态类MyExtensions 
{
公共静态无效AddToFront< T>(名单< T>清单,T项)
{
//忽略验证等
list.Insert(0项);
}
}

//别处

名单,LT; INT>名单=新名单,LT; INT>();
list.Add(2);
list.AddToFront(1);
//名单现在1,2



但同样,你没有得到什么您还没有。


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. Can someone help me out with this?

myList.AddToFront(T object);

解决方案

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.

这篇关于T&GT;的名单,LT扩展方法; AddToFront(T对象)怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆