【问题标题】:what is the difference between Stack st = new Stack() and Stack<string> names = new Stack<string>(); in c#Stack st = new Stack() 和 Stack<string> names = new Stack<string>(); 有什么区别?在c#中
【发布时间】:2017-10-22 18:49:35
【问题描述】:

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

Stack st = new Stack()

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

【问题讨论】:

标签: c# generics collections generic-collections


【解决方案1】:

在这种情况下Stack&lt;string&gt; names = new Stack&lt;string&gt;(); 你只能将“字符串”放入堆栈,而在这种Stack st = new Stack(); 中你可以放入任何对象。

【讨论】:

    【解决方案2】:

    这是两个不同的集合。第一个在命名空间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&lt;string&gt;() 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.
    

    并不是第一个示例在运行时产生异常(这很糟糕),而第二个示例会产生编译器错误并在您编写代码时通知您该问题。

    建议:始终使用泛型集合。

    【讨论】:

      猜你喜欢
      • 2014-05-24
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 2017-04-05
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多