【发布时间】:2017-10-22 18:49:35
【问题描述】:
两者的主要区别是什么,哪个更好。我们可以在两者中添加数据组合吗?有什么区别
Stack st = new Stack()
和
Stack<string> names = new Stack<string>();
【问题讨论】:
标签: c# generics collections generic-collections
两者的主要区别是什么,哪个更好。我们可以在两者中添加数据组合吗?有什么区别
Stack st = new Stack()
和
Stack<string> names = new Stack<string>();
【问题讨论】:
标签: c# generics collections generic-collections
在这种情况下Stack<string> names = new Stack<string>(); 你只能将“字符串”放入堆栈,而在这种Stack st = new Stack(); 中你可以放入任何对象。
【讨论】:
这是两个不同的集合。第一个在命名空间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.
第二个是通用的。 IE。您可以指定堆栈打算存储的项目类型。它是强类型的。
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.
并不是第一个示例在运行时产生异常(这很糟糕),而第二个示例会产生编译器错误并在您编写代码时通知您该问题。
建议:始终使用泛型集合。
【讨论】: