您的位置:首页 > 编程语言 > C#

C#第7周泛型类的使用

2016-04-23 17:38 447 查看
 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();

}
}
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: