初始情况:
我正在使用一种专有的框架(ESRI的ArcGIS Engine)进行操作,我想要为其添加一些新的功能。我选择使用C#中的扩展方法来完成。
以下是与此问题相关的框架API的部分:
+------------------------+ IGeometry
| IFeature <interface> | <interface>
+------------------------+ ^
| +Shape: IGeometry | |
+------------------------+ +---------+---------+
| |
IPoint IPolygon
<interface> <interface>
我想要做的事情:
我想为IFeature
编写一个扩展方法,使其能够实现以下功能:
IFeature featureWithPointShape = ...,
featureWithPolygonShape = ...;
// this should work:
featureWithPointShape.DoSomethingWithPointFeature();
// this would ideally raise a compile-time error:
featureWithPolygonShape.DoSomethingWithPointFeature();
问题在于点和多边形形状(
IPoint
和 IPolygon
)都被包装在同一类型中(IFeature
),扩展方法是定义在该类型上的。扩展方法必须在 IFeature
上,因为我只能从 IFeature
得到其 IGeometry
,但反过来不行。
问题:
虽然可以在运行时轻松检查 IFeature
对象的 Shape
类型(请参见下面的代码示例),但我如何在编译时实现此类型检查呢?
public static void DoSomethingWithPointFeature(this IFeature feature)
{
if (!(feature.Shape is IPoint))
{
throw new NotSupportedException("Method accepts only point features!");
}
... // (do something useful here)
}
有没有可能使用通用的包装类型
FeatureWithShape<IPoint>
作为IFeature
的包装器,并在该包装类型上定义扩展方法,然后将所有IFeature
对象转换成此包装器类型呢?
FeatureWithShape<IPoint> : IFeature
的包装器,并指定一个显式的操作符:http://msdn.microsoft.com/en-us/library/xhbhezf4(VS.90).aspx - Joseph YaduvanshiIFeature
接口(它包含了无数东西)。有没有一种方法可以实现一个接口类型的包装器,它的行为与接口类型本身完全相同,但将大部分实际工作委托给被包装的对象(该对象是接口类型)? - stakx - no longer contributing