小菜的ArcObjects学习之路------C#中接口的转换

来源:互联网 发布:mac好用的邮件客户端 编辑:程序博客网 时间:2024/05/21 15:42
Casting in C#
In C#, the best method for casting between interfaces is to use the as operator. Using the as operator is a better coding strategy than a straight cast, because it yields a null on a conversion failure rather than raising an exception. 

The first line in the following code example is a straight cast. This is an acceptable practice if you are certain the object in question implements both interfaces. If the object does not implement the interface you are attempting to get a handle to, .NET throws an exception. A safer model to use is the as operator, which returns a null if the object cannot return a reference to the desired interface.
[C#]
IGeometry geometry = (IGeometry)point; // Straight cast.
IGeometry geometry = point as IGeometry; // As operator.
The following code example shows how to manage the possibility of a returned null interface handle after an explicit cast:
[C#]
IPoint point = new PointClass();
IGeometry geometry = point as IGeometry;
if (geometry != null)
{
    Console.WriteLine(geometry.GeometryType.ToString());
}
Alternatively, you can test if an object implements a certain interface at run time using the is keyword before performing a straight cast. See the following code example:
[C#]
IPoint point = new PointClass();
if (point is IGeometry)
{
    IGeometry geometry = (IGeometry)point;
    Console.WriteLine(geometry.GeometryType.ToString());
}

翻译:
    在C#中强制转换接口的方法是使用as操作符。使用as操作符是比直接转换更好的编码策略,因为他转换失败时返回null值,而不是抛出一个异常。面的第一行实例代码使用的是直接转换,只有你确定该对象实现了该接口,才是可以接受的操作,如果对象没有实现你想尝试的接口将会抛出异常。一个安全的使用方法是选用as操作符,当无法返回想要接口的引用是将会返回null
[C#]
IGeometry geometry = (IGeometry)point;   // Straight cast.
IGeometry geometry = point as IGeometry; // As operator.

一下代码显示如果处理转换异常情况
[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());
}



原创粉丝点击