【问题标题】:stack oftype<> option how to work [closed]stack oftype<> 选项如何工作[关闭]
【发布时间】:2013-02-13 15:56:10
【问题描述】:

谁能告诉我如何使用stack.ofType&lt;&gt;?我试了很多次都做不到。

private void button2_Click(object sender, EventArgs e)
{
    Stack st = new Stack();
    st.Push("joginder");
    st.Push("singh");
    st.Push("banger");
    st.Push("Kaithal");
    st.OfType<>  //how to work this option
}

【问题讨论】:

  • 不清楚,你要做什么。
  • 您只是在堆栈中插入字符串,因此OfType&lt;&gt;() 给您带来的好处尚不清楚。你能详细说明你想要达到的目标吗?

标签: c# asp.net


【解决方案1】:

使用通用的Stack&lt;T&gt; 类型而不是Stack,这样您将获得特定类型的堆栈,并且您不必转换从中读取的值:

Stack<string> st = new Stack<string>();
st.Push("joginder");
st.Push("singh");
st.Push("banger");
st.Push("Kaithal");

现在,当您从堆栈中弹出某些内容或循环遍历项目时,它已经是一个字符串,您不必强制转换它。

【讨论】:

    【解决方案2】:

    你提供一个像这样的类型

    st.OfType<string>()
    

    这会返回一个 IEnumerable 供您进行迭代,而不会将任何项目从堆栈中弹出。

    鉴于此代码:

            Stack st = new Stack();
            st.Push("joginder");
            st.Push("singh");
            st.Push("banger");
            st.Push("Kaithal");
            st.Push(1);
            st.Push(1.0);
    
            foreach (var name in st.OfType<string>())
            {
                Console.WriteLine(name);
            }
    

    你会得到这个输出:

     joginder
     singh
     banger
     Kaithal
    

    【讨论】:

    • 感谢您分享宝贵的时间。
    【解决方案3】:

    使用genericsStack&lt;T&gt;

    private void button2_Click(object sender, EventArgs e)
        {
            Stack<string> st = new Stack<string>();
            st.Push("joginder");
            st.Push("singh");
            st.Push("banger");
            st.Push("Kaithal");
     }
    

    你也可以这样做:

    public class Client {
        public string Name { get; set; }
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
            Stack<Client> st = new Stack<Client>();
            st.Push(new Client { "joginder" });
            st.Push(new Client { "singh" });
            st.Push(new Client { "banger" });
    
    }
    

    注意类 Client 是为了演示如何将 T 替换为您分配的类型。

    【讨论】:

      【解决方案4】:

      这里有一个很好的例子:http://msdn.microsoft.com/en-us/library/bb360913.aspx,但是,基本上您可以使用 OfType 来创建该特定类型的项目的 IEnumerable,例如,如果您的代码读取:

              Stack st = new Stack();
              st.Push("joginder");
              st.Push(1.4);
              st.Push("singh");
              st.Push("banger");
              st.Push(2.8); 
              st.Push("Kaithal");
      
              IEnumerable<String> strings = st.OfType<String>();  //how to work this option
              IEnumerable<double> doubles = st.OfType<double>();   
      

      将创建“列表”,一个包含堆栈中的所有字符串,一个包含所有双精度数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-31
        • 2015-04-10
        • 1970-01-01
        • 1970-01-01
        • 2013-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多