Stack st = new Stack()和Stack <string> names = new Stack <string>();有什么区别?在c#中

时间:2017-10-22 18:49:35

标签: c# generics collections generic-collections

它们的主要区别在于哪个更好。我们可以在两者之间添加数据组合吗?有什么区别

Stack<string> names = new Stack<string>();

xterm -e less file.c

2 个答案:

答案 0 :(得分:0)

在这种情况下Stack<string> names = new Stack<string>();你只能输入&#34; string&#34;在堆栈中,在这个Stack st = new Stack();中你可以放置任何对象。

答案 1 :(得分:0)

这是两个不同的集合。第一个位于名称空间System.Collections中,第二个位于名称空间System.Collections.Generic中。

第一个(非通用的)存储类型object的值。

public virtual void Push(object obj)
public virtual object Pop()

由于C#中的所有类型都派生自object,因此您可以在此堆栈中存储任何类型的值。缺点是,在添加到集合之前,必须将值类型加框,即封装到对象中。在检索时,它们必须是未装箱的。你也没有类型安全。

示例:

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.

第二个是通用的。即您可以指定堆栈要存储的项目类型。它是强类型的。

public void Push(T item)
public T Pop()

new Stack<string>() T替换为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.

不是第一个例子在运行时产生异常(这是坏的),而第二个例子产生编译器错误并在编写代码时通知你这个问题。

建议:始终使用通用集合。

相关问题