Allocate stack size in C#?
I am developing a virtual machine for a byte code language I have been working on. I am using the System.Collections.Generic.Stack
class for the stack but is there any way to allocate the stack size? Or do I ju开发者_如何学Cst have to write my own stack object to use?
From MSDN for the Stack(Int32) constructor:
The capacity of a Stack is the number of elements that the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required by reallocating the internal array.
If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Stack.
The capacity can be decreased by calling TrimExcess.
This constructor is an O(n) operation, where n is capacity.
You can construct it with an initial capacity, but the stack will grow as needed (as you add items to it).
If you do not want it to automatically add new items when you push it past it's capacity, you'll need to encapsulate it in your own class or write your own Stack which removes the excess items.
You can use the Stack<T> Constructor (Int32) to specifiy the capacity of the stack:
var stack = new Stack<Foo>(1024);
Note that the stack will grow the capacity if you add more than 1024 items. If you don't want this, you can check the stack size before each push:
if (stack.Count == 1024)
throw new StackOverflowException();
stack.Push(foo);
you can - see http://msdn.microsoft.com/en-us/library/ahc986x9.aspx
Your terminology leaves a lot to be desired, but Stack
has a constructor that allows you to pass an initial capacity: http://msdn.microsoft.com/en-us/library/ahc986x9.aspx
The stack is free to grow as large as you have memory though, so you don't need to worry about that!
Stack(T) Class
Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.
It resizes it self dynamically. But if you want to preallocate its size then check out the documentation on the Stack's constructor. There's an overload with which you can set the stack's initial size.
精彩评论