Unity C# 기본 검토 21 - 일반 컬렉션 2, 해시 테이블 및 사전(P393)

1. 제네릭의 장점은 키와 값의 유형을 특정 고정 유형으로만 제한한다는 것입니다.

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