1. La ventaja de los genéricos es que limitan los tipos de clave y valor solo a ciertos tipos fijos.
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); //返回规定是什么类型就是什么类型
}
}
}
}
La importancia de los genéricos
1. Las colecciones genéricas tienen más seguridad de tipos que las colecciones tradicionales.
2. Las colecciones genéricas no requieren operaciones de boxing y unboxing.
3. Resuelva muchos problemas que requieren operaciones engorrosas.
4. Proporciona una mejor seguridad tipográfica