Unity C# 基础复习21——泛型集合2、哈希表和字典(P393)

1、泛型的好处就在于限定key和value的类型只能是某种固定类型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace Test01
{
    class Student 
    {
        public int num;
        public string name;
    }
    class Teacher 
    {

    }
    class Program
    {
        static void Main(string[] args)
        {
            TestHashDictionary();
        }

        public static void TestHashDictionary() 
        {
            Hashtable ht = new Hashtable();
            Student s = new Student();
            s.name = "小明";
            s.num = 1;
            //这种情况我们按num和name去搜索s,管理比较混乱
            ht.Add(s.num, s);
            ht.Add(s.name, s);

            //哈希表的遍历情况,需要做判断和强转(拆箱和装箱)
            foreach (var item in ht.Keys)
            {
                //Console.WriteLine(item);  item是Object类型
                if (item is String) 
                {
                    String name = item as String;
                }
                if (item is int) 
                {
                    int num = (int)item;//强制转换
                }
            }
            
            //遍历
            foreach (DictionaryEntry item in ht)
            {
                Console.WriteLine(item.Key + " = " + item.Value);  //这边返回都是Object
            }


            Dictionary<int, Student> stus = new Dictionary<int, Student>();
            //stus.Add(s.name, s);   不允许以s.name索引
            stus.Add(s.num, s);      //只允许以整型索引

            //字典的遍历情况,不需要拆箱装箱
            foreach (var item in stus.Keys)
            {
                int num = item;
                Console.WriteLine(num);
            }

            //遍历
            foreach (KeyValuePair<int, Student> item in stus)
            {
                int num = item.Key;
                Student stus_item = item.Value;
                Console.WriteLine(num + " = " + stus_item);  //返回规定是什么类型就是什么类型
            }
        }
    }
}

泛型的重要性

1、泛型集合与传统集合相比类型更加安全

2、泛型集合无需装箱拆箱操作

3、解决了很多需要繁琐操作的问题

4、提供了更好的类型安全性

 

猜你喜欢

转载自blog.csdn.net/weixin_46711336/article/details/124847221