using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03_字典的封装
{
internal class Program
{
static void Main(string[] args)
{
MyDic myDic = new MyDic();
myDic.Add("name", 123);
myDic.Add("age", 10);
myDic.Add("gender", 1);
myDic.Add("height", 170);
myDic.Add("weight", 60);
myDic.Remove ("name");
List<string> keys = myDic.Keys;
for (int i = 0; i < keys.Count; i++)
{
Console.WriteLine(keys[i]);
}
Console.WriteLine(myDic.Count );
Console.WriteLine(myDic["name"]);
Console.ReadLine();
}
}
// 自己封装的字典类
class MyDic
{
string[] keys = new string[4];// 存储所有的键
int[] values = new int[4];// 存储所有的值
// 定义属性获取字典中的数据长度
public int Count { get; private set; } = 0;
public List<string> Keys
{
get
{
List<string> keys = new List<string>();
for (int i = 0; i < Count; i++)
{
keys.Add(this.keys[i]);
}
return keys;
}
}
public List<int> Values
{
get
{
List<int> values = new List<int>();
for (int i = 0; i < Count; i++)
{
values.Add(this.values[i]);
}
return values;
}
}
public void Add(string key, object value)
{
UpdateCapacity(Count + 1);
// 将添加的数据放到数组的最后一位
keys[Count] = key;
values[Count] = (int)value;
Count++;
}
public int this[string key]
{
get
{
int index = IndexOf(key);
if (index == -1)
{
// default(int) 获取指定的类型的默认值
return default(int);
}
return values[index];
}
set
{
int index = IndexOf(key);
if (index != -1)
{
values[index] = value;
}
}
}
int IndexOf(string key)
{
for (int i = 0; i < Count; i++)
{
if (keys[i] == key)
{
return i;
}
}
return -1;
}
// 获取存储数据的空间大小应该是多大
// 获取数据的长度
// 更新存储数据的容量
public void UpdateCapacity(int lenth)
{
int capa = GetCapacity(lenth);
if ( capa != keys.Length )
{
// 将键对应的空间大小改变一下
string[] newKeys = new string[capa];
for (int i = 0; i < Count ; i++)
{
newKeys[i] = keys[i];
}
keys = newKeys;
// 将值对应的空间大小改变一下
int[] newValues = new int[capa];
for (int i = 0; i < Count ; i++)
{
newValues[i] = values[i];
}
values = newValues;
}
}
public int GetCapacity(int lenth)
{
// 定义变量存储开始的空间大小
int Capacity = 4;
while (Capacity < lenth)
{
Capacity *= 2;
}
return Capacity;
}
public void Remove(string key)
{
int index = IndexOf(key);
if (index != -1)
{
for (int i = index; i < Count-1 ; i++)
{
keys[i] = keys[i + 1];
values[i] = values[i + 1];
}
Count--;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02_学生字典案例
{
internal class Program
{
static void Main(string[] args)
{
Dictionary<string,string>student = new Dictionary<string, string>();
student.Add("name", "张三");
student.Add("age", "20");
student.Add("score", "80");
Dictionary<string, string> student1 = new Dictionary<string, string>();
student1.Add("name", "李四");
student1.Add("age", "18");
student1.Add("score", "80");
Dictionary<string, string> student2 = new Dictionary<string, string>();
student2.Add("name", "王五");
student2.Add("age", "20");
student2.Add("score", "90");
}
}
}