stack oftype<>选项如何工作

时间:2013-02-13 15:56:10

标签: c# asp.net

有谁能告诉我如何使用stack.ofType<>?我已经尝试了很多次但是不能这样做。

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
}

4 个答案:

答案 0 :(得分:4)

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

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

现在当你从堆栈中弹出一些东西,或者循环遍历这些项目时,它已经是一个字符串了,你不需要强制转换它。

答案 1 :(得分:1)

您提供类似的类型

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

答案 2 :(得分:0)

这里有一个很好的例子: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>();   

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

答案 3 :(得分:0)

使用genericsStack<T>

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" });

}

请注意,客户端类将演示如何为您指定的类型替换T

相关问题