何时使用Stack< T>在C#中收集? [英] When to use the Stack<T> collection in C#?

查看:100
本文介绍了何时使用Stack< T>在C#中收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白如何 Stack() Stack< T> 的作品,但我真的看不到数组 List< T> IEnumerable< T> 的任何场景不是更好和更容易的选择。



任何人都可以为我提供使用 Stack< T>

的真实世界示例b $ b

解决方案

理想情况下,您可以根据需要使用或创建反映事物在现实世界中工作的类,即代码中建模的东西。这样的类给了我们一个抽象级别,所以我们可以根据我们的建模/模拟来编写代码。另外编码一些复杂的东西时,使用熟悉的范例有助于。呃,这个Fuzzinator类使用一个Stack。我知道一个堆栈是什么,它是如何工作的。



其次,这个更高级别的抽象类给了我们代码(我们假设.NET框架是测试),并节省了我们重新创造轮子的时间和痛苦。



第三,代码更容易阅读,更容易理解,更容易更改等。更可维护。



使用具有更精致功能的类可帮助限制我们如何使用它。



整体而言,当您的应用程序在适当的抽象级别进行编码时,简单地



堆栈是其中一个类。 p>

我的HP-41X计算器使用堆栈进行算术。这种计算方法称为RPN - 反向波兰符号。



如果我正在模拟一个自助餐厅,堆栈将是完美的堆栈板。板从顶部开始和关闭堆栈。不是中间,不是结束;只是顶部。一个堆栈我只能Push()和Pop()板,这使得代码更简单明了。



或者,想象使用C#等效的子原子粒子 - 通用集合或通用IEnumerable等进行编码。我最终使用通用实用程序方法和属性,多个可变数量的参数总体上掩盖了我正在堆叠的事实。


I do understand how Stack() and Stack<T> works, but I really can't see any scenarios where an array, List<T> or IEnumerable<T> isn't a better and easier choice.

Can anyone provide me a real world example of the use of Stack<T>?

解决方案

Ideally you use, or create as needed, classes that reflect how things work in the real world, the things you are modeling in code. Such classes give us a level of abstraction so we can code in terms of what we are modeling/simulating. Additionally when coding some complex thing, using a familiar paradigm helps. To wit: Oh, this Fuzzinator class uses a Stack. I know what a stack is and how it works.

Second, that higher-level-of-abstraction class gives us code that works (we assume the .NET framework was tested) and saves us the time and pain of re-inventing the wheel.

Third, the code is easier to read, easier to understand, easier to change and so on. It is more maintainable.

Using classes with more refined functionality helps limit how we might screw up in using it.

On the whole your application is simply better when it's coded at appropriate levels of abstraction.

Stack is one of these classes.

My HP-41X calculator does its arithmetic using a stack. This way of calculation is called RPN - Reverse Polish Notation.

If I were simulating a cafeteria the Stack would be perfect for that stack of plates. Plates get on and off the stack from the top. Not the middle, not the end; just the top. A Stack. I can only Push() and Pop() plates which makes the code more simple and clear.

Alternatively, imagine coding with the C# equivalent of sub-atomic particles - generic collection or generic IEnumerable, etc. I end up using general utility methods and properties with general names with multi-variable numbers of parameters which in the aggregate obscure the fact that I'm stacking plates.

这篇关于何时使用Stack&lt; T&gt;在C#中收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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