事件為類和類的實例提供了向外界發送通知的能力,而索引指示器則可以象數組那樣對對象進行索引訪問。在C和C++中,沒有事件和索引指示器的概念,它們是在C#中首次提出的。
13.1 C#的事件(event)
13.2 索引指示器
索引指示器(indexer)可以象數組那樣對對象使用下標。它為我們提供了通過索引方式方便地訪問類的數據信息的方法。
13.2.1 C#索引指示器的聲明
13.2.2 實例
本實例給出運用索引指示器的一個簡單例子。例子是一個網絡應用程序:根據域名解析IP地址。
程序清單13-5:
using System;
using System.Net;
class ResolveDNS
{
IPAddress[] m_arrayIPs;
public void Resolve(string s_host){
IPHostEntry ip=DNS.GetHostByName(s_host);
m_arrayIPs=ip.AddressList;
}
public IPAddress this[int nIndex]{
get{
return m_arrayIPs[nIndex];
}
}
public int IPLength{
get{
return m_arrayIPs.Length;
}
}
}
class TestApp
{
public static void Main()
{
ResolveDNS resolver1=new ResolveDNS();
resolve1.Resove(www.sohu.com);
int n=resolver1.IPLength;
Console.WrieLine("Get the IP Address of the host");
Console.WriteLine();
for(int i=0;i〈n;i++)
Console.WriteLine(resover1[i]);
}
}
程序的幾點說明:
使用System.Net名字空間中的DNS類可以解析主機名。DNS類中提供了一個靜態方法GetHostByName,這個方法返回一個IPHostEntry對象,這個對象中含有IP地址列表。
在編譯該程序時,必須在編譯器中聲明包含System.Net名字空間:
csc/r:System.Net.dll/out:resolver.exe resover.cs
有關csc的編譯參數可以使用csc/?來浏覽。