Welcome

首页 / 软件开发 / C# / C#的事件和索引指示器

C#的事件和索引指示器2007-09-25 本站 事件为类和类的实例提供了向外界发送通知的能力,而索引指示器则可以象数组那样对对象进行索引访问。在C和C++中,没有事件和索引指示器的概念,它们是在C#中首次提出的。

13.1

13.2 索引指示器

索引指示器(indexer)可以象数组那样对对象使用下标。它为我们提供了通过索引方式方便地访问类的数据信息的方法。

13.2.1

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/?来浏览。