C#第7周泛型类的使用

本文介绍了C#中如何利用System.Collections命名空间下的泛型类Stack<T>和Queue<T>进行数据操作,如数字或字符串的反序、数值型数据的入队与出队及求和。同时,通过一个匿名方法的委托展示了计算整数数组元素之和的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1.引入命名空间System.Collections,使用.Net提供的泛型类Stack<T>,实现数字或字符串的反序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack<string> m = new Stack<string>();
            string s = Console.ReadLine();
            char[] a = s.ToCharArray();
            for (int i = 0; i < a.Length; i++)
            {
                m.Push(a[i].ToString());
            }
            while (m.Count > 0)
            {
                Console.Write(m.Pop());
            }
            Console.ReadKey();
        }
    }
}

2.引入命名空间System.Collections,使用.Net提供的泛型类Queue<T>,实现任意数值型数据的入队,出队操作。并将出队的数据求和。

using System;
using System.Collections;
using System.Collections.Generic;
namespace Program0
{
    class Program
    {

        static void Main(string[] args)
        {

            Queue<int> t = new Queue<int>();
            int[] a = { 1,2,3,4,5};
            int sum = 0;
            for (int i = 0; i < a.Length; i++)
            {
                t.Enqueue(a[i]);
            }
            while (t.Count > 0)
            {
                sum += t.Peek();
                Console.Write("{0} ", t.Dequeue());
            }
            Console.WriteLine("出队数据之和为:{0}", sum);
            Console.ReadKey();
        }
    }

}


3.编写一个使用匿名方法的委托,匿名方法实现计算整数型数组各元素之和的功能。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication2
{
    delegate void mydelegate(int[] a);

    class Program
    {
        static void Main(string[] args)
        {
            mydelegate d = delegate(int[] a)
            {
                int sum = 0;
                foreach (int item in a)
                {
                    sum += item;
                }
                Console.WriteLine(sum);
            };
            int[] aa = { 1, 2, 3, 4, 5 };
            d(aa);
            Console.ReadKey();

        }
    }
}


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值