为什么我不能在 C# 中转换 com 对象?

Why cannot I cast com object in c#?

源代码:

   IMoniker moniker;
    int hresult = NativeMethods.CreateFileMoniker(kFileName, out moniker);
    IBindCtx pbc;
    NativeMethods.CreateBindCtx(0, out pbc);
    Object obj;
    Guid guid = new Guid();
    guid = typeof(GraphicsLibrary.IPolyline).GUID;
    moniker.BindToObject(pbc, null, guid, out obj);
    GraphicsLibrary.IPolyline pl = (GraphicsLibrary.IPolyline)obj;
    GraphicsLibrary.PolylineObjClass o = (GraphicsLibrary.PolylineObjClass)pl;
    foreach (GraphicsLibrary.PolyPoint ptt in o.Points)
    {
        Trace.WriteLine(String.Format("point ({0}, {1})", ptt.x, ptt.y));
    }
    return 0;

GraphicsLibrary.PolylineObjClass o = (GraphicsLibrary.PolylineObjClass)pl;

异常

详情:

An exception of type 'System.InvalidCastException' occurred in DotNetClient.exe but was not handled in user code

但是我已经实现了 IProvideClassInfo 接口并注册了类型库。

为什么我无法投射对象?

PS:完整源码,请参考https://github.com/Jichao/comtut/tree/master/monikers/FileMoniker

您的对象是 IPolyline 的实现,并非来自 PolylineObjClass 的任何超类或 PolylineObjClass 本身。

  • A 实施 IPolyline
  • B 实施 IPolyline
  • myFirstObj = new B();
  • mySecondObj = (A) myFirstObj; <= 失败,因为 B 可能会实现其他方法或属性 A 不会,所以无法转换
  • mySecondObj = (IPolyline) myFirstObj; <= 工作,你被限制在相同的方法范围内。