Unity C# Basic Review 21 - Generic Collection 2, Hash Table and Dictionary (P393)

1. The advantage of generics is that they limit the types of key and value to only certain fixed types.

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);  //返回规定是什么类型就是什么类型
            }
        }
    }
}

The importance of generics

1. Generic collections are more type-safe than traditional collections

2. Generic collections do not require boxing and unboxing operations

3. Solve many problems that require cumbersome operations

4. Provides better type safety

 

 

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/124847221