索引器示例代码
/// <summary>
/// 存储星期几的类。声明了一个get访问器,它接受字符串,并返回相应的整数
/// </summary>
public class 星期
{
public string[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
//索引器 它接受星期几的字符串,将它作为索引index
public int this[string day]
{
//get访问器 并返回相应的整数
get
{
int i = 0;
foreach (var item in weeks)
{
if (item == day)
{
return i;
}
i++;
}
//没找到返回-1
return -1;
}
}
}
Hashtable示例代码
//方法一
foreach (System.Collections.DictionaryEntry de in myHashtable)
{
//注意HastTable内存储的默认类型是object,需要进行转换才可以输出
Console.WriteLine(de.Key.ToString());
Console.WriteLine(de.Value.ToString());
}
//方法二
System.Collections.IDictionaryEnumerator enumerator = myHashtable.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Key); // Hashtable关健字
Console.WriteLine(enumerator.Value); // Hashtable值
}
//遍历键
foreach (string key in myDictionary.Keys)
{
//遍历某键的值
foreach (string val in myDictionary[key])
{
}
}
字典遍历示例
foreach (KeyValuePair<string, string> kvp in myDictionary)
{
string key = kvp.Key;//key包含了字典里的键
for (int i = 0; i < kvp.Value.Count; i++)
{
Response.Write(kvp.Value[i]);
}
}
//定义一个<string,int>的Dictionary,让它的值进行添加(也可以用Add方法)
Dictionary<string, int> dic = new Dictionary<string, int>();
//添加两个键为"成绩1","成绩2";并为它们的值赋为0
dic["成绩1"] = 0;
dic["成绩2"] = 0;
// 把这两个值分别加1
dic["成绩1"]++;
dic["成绩2"]++;