c#自学之路第十六天
一、笔记
1.装箱、拆箱
装箱:就是将值类型转换为引用类型
拆箱:将引用类型转换为值类型 看两种类型是否发生了装箱和拆箱,要看,这两个类型是否存在继承关系。
2.字典集合Dictionary
在遍历的时候可以以一对一对的出来
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "张三");
dic.Add(2, "李四");
dic.Add(3, "王五");
dic[1] = "新来的";
//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();
二、代码
namespace 装箱和拆箱
{
class Program
{
static void Main(string[] args)
{
int n = 10;
object o = n;//装箱
int nn = (int)o;//拆箱
//ArrayList list = new ArrayList();
List<int> list = new List<int>();
//发生了100万次装箱操作
Stopwatch sw = new Stopwatch();
sw.Start();
for(int i=0;i<10000000;i++)
{
list.Add(i);
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadKey();
}
}
}
namespace 字典集合
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "张三");
dic.Add(2, "李四");
dic.Add(3, "王五");
dic[1] = "新来的";
//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();
}
}
}
namespace 字典集合的练习
{
class Program
{
static void Main(string[] args)
{
#region 问题一
//将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中
//最后将两个集合合并为一个集合,并且奇数显示到左边,偶数返回到右边
//int[] nums = { 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<nums.Length;i++)
//{
// if(nums[i]%2==0)
// {
// listou.Add(nums[i]);
// }
// else
// {
// listji.Add(nums[i]);
// }
//}
//listji.AddRange(listou);
//foreach (var item in listji)
//{
// Console.Write(item+" ");
//}
//Console.ReadKey();
#endregion
#region 问题二
//提示用户输入一个字符串,通过foreach循环将用户输入的字符串赋值给一个字符串数组
//Console.WriteLine("请输入一个字符串");
//string input = Console.ReadLine();
//int i = 0;
//char[] chs = new char[input.Length];
//foreach (var item in input)
//{
// chs[i] = item;
// i++;
//}
//foreach (var item in chs)
//{
// Console.WriteLine(item);
//}
//Console.ReadKey();
#endregion
//统计welcome to china中每个字符串出现的次数 不考虑大小写
string str = "welcome to China";
Dictionary<char, int> dic = new Dictionary<char, int>();
for(int i = 0;i<str.Length;i++)
{
if(str[i]==' ')
{
continue;
}
if(dic.ContainsKey(str[i]))
{
dic[str[i]]++;
}
else
{
dic[str[i]] = 1;
}
}
foreach (KeyValuePair<char,int> kv in dic)
{
Console.WriteLine("字母{0}出现了{1}次",kv.Key,kv.Value);
}
Console.ReadKey();
}
}
}