为什么总会有使用堆叠< T>而不是List< T>?总会有、而不是、GT、LT

2023-09-04 23:56:42 作者:时间不会说话

名单,其中,T> System.Collections.Generic 做的一切堆栈< T&GT ; 呢,等等 - 他们是基于相同的底层数据结构。在什么条件下是正确的选择堆栈< T> 而不是

List<T> from System.Collections.Generic does everything Stack<T> does, and more -- they're based on the same underlying data structure. Under what conditions is it correct to choose Stack<T> instead?

推荐答案

您会使用堆栈,如果你有一个需要一个最后在项目的先出集合。名单将允许您访问它的项目在任何索引。还有很多其他方面的差异,但我会说这是最根本的。

You would use stack if you had a need for a Last In First Out collection of items. A list will allow you to access it's items at any index. There are a lot of other differences but I would say this is the most fundamental.

您的评论后更新:

我要说的是,使用堆栈&LT; T&GT; 使你想怎样使用这个code语句。这是一件好事,规划未来,但如果你有需要堆栈&LT; T&GT; 现在,并没有令人信服的理由使用名单,其中, T&GT; 然后,我将与去堆栈&LT; T&GT;

I would say that using Stack<T> makes a statement about how you want this code to be used. It's always good to plan for the future, but if you have a need for Stack<T> right now, and no compelling reason to use List<T> then I would go with Stack<T>