装箱和拆箱
//int n = 10;
//object o = n;//装箱
//int nn = (int)o;//拆箱
//代码中应该避免装箱和拆箱
ArrayList list = new ArrayList();
//这个过程进行了1000万次装箱
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000000; i++)
{
list.Add(i);
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
Dictionary键值对
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "张三");
dic.Add(2, "李四");
dic.Add(3, "王五");
//foreach (var item in dic.Keys)//这是遍历建 不洋气
//{
// Console.WriteLine("{0}----{1}", item, dic[item]);
//}
foreach (KeyValuePair<int, string> kv in dic)//这是键值对 更洋气
{
Console.WriteLine("{0}----{1}", kv.Key, kv.Value);
}
Console.ReadKey();
泛型集合的练级
1.
将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中
最终将两个集合合并成一个集合,并且将奇数放到左边 偶数显示到右边
int[] sum = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<int> listou = new List<int>();
List<int> listji = new List<int>();
for (int i = 0; i < sum.Length; i++)
{
if (i % 2 == 0)
{
listou.Add(i);
}
else
{
listji.Add(i);
}
}
listji.AddRange(listou);
foreach (var item in listji)
{
Console.Write(item + " ");
}
Console.ReadKey();
2.
提示用户输入一个字符串 通过foreach循环将用户输入的字符串赋值给一个char类型的数组
Console.WriteLine("输入一个字符串");
string input = Console.ReadLine();
char[] chas = new char[input.Length];
int i = 0;
foreach (var item in input)
{
chas[i] = item;
i++;
}
foreach (var item in chas)
{
Console.WriteLine(item);
}
Console.ReadKey();