ArcObjects编程方法(二):接口类型转换

版本:ArcGIS 10   

在C#中,相对直接转换,最好通过as操作符进行接口类型转换。通过as操作符进行类型转换失败时,会返回null值,而不是抛出异常。

下面的代码演示了两种不同转换的形式:

[C#]

IGeometry geometry = (IGeometry)point; // 直接转换
IGeometry geometry = point as IGeometry; // As操作符转换

下面代码演示如何应对类型转换造成的空值:

[C#]

IPoint point = new PointClass();
IGeometry geometry = point as IGeometry;
if (geometry != null)
{
    Console.WriteLine(geometry.GeometryType.ToString());
}

可以用is关键字判断变量是否为特定接口类型:

[C#]

IPoint point = new PointClass();
if (point is IGeometry)
{
    IGeometry geometry = (IGeometry)point;
    Console.WriteLine(geometry.GeometryType.ToString());
}
posted @ 2011-09-23 16:49  xmwang  阅读(669)  评论(0编辑  收藏  举报