다음은 두 가지 컬렉션입니다. 첫 번째 것은 네임 스페이스 System.Collections
에 있고 두 번째 것은 네임 스페이스 System.Collections.Generic
에 있습니다.
첫 번째 (비 일반형)는 object
유형의 값을 저장합니다. C#에서 모든 종류의 object
에서 파생 때문에
public virtual void Push(object obj)
public virtual object Pop()
, 당신은이 스택에서 값의 어떤 종류를 저장할 수 있습니다. 단점은 컬렉션에 추가되기 전에 값 유형을 박스로 묶어야합니다 (즉, 객체에 캡슐화해야 함). 검색 중에는 언 박싱해야합니다. 또한 유형 안전성이 없습니다.
예 :
Stack st = new Stack();
st.Push("7");
st.Push(5); // The `int` is boxed automatically.
int x = (int)st.Pop(); // 5: You must cast the object to int, i.e. unbox it.
int y = (int)st.Pop(); // "7": ERROR, we inserted a string and are trying to extract an int.
두 번째는 일반적이다. 나는. 스택이 저장할 항목 유형을 지정할 수 있습니다. 강하게 입력됩니다. new Stack<string>()
T
하여 예에서
public void Push(T item)
public T Pop()
는
string
public void Push(string item)
public string Pop()
실시 예로 대체되어
첫번째 예는 있지만, (불량) 런타임 예외를 생성하지 않는 것이
Stack<string> names = new Stack<string>();
names.Push("John");
names.Push(5); // Compiler error: Cannot convert from 'int' to 'string'
string s = names.Pop(); // No casting required.
두 번째는 컴파일러 오류를 생성하고 코드를 작성하는 동안 문제에 대해 알려줍니다.
조언 : 항상 제네릭 컬렉션을 사용하십시오.
[안전과 성능을 향상시키기 위해 일반 컬렉션을 사용해야합니까?] (https://stackoverflow.com/questions/264496/should-we-use-generic-collection-to-improve-safety-and- 성능) – glennsl
제네릭을 읽으시기 바랍니다 : https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/ –