Jichao
Jichao

Reputation: 41845

Why cannot I cast com object in c#?

The source code:

   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;

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

Detail:

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

But I have implemented the IProvideClassInfo interface and did register the typelib.

Why cannot I cast the object?

PS: full source code, please refer https://github.com/Jichao/comtut/tree/master/monikers/FileMoniker

Upvotes: 0

Views: 78

Answers (1)

z1pm4n
z1pm4n

Reputation: 61

Your object is an implementation of IPolyline and do not comes from any superclass of PolylineObjClass or PolylineObjClass itself.

  • A implements IPolyline
  • B implements IPolyline
  • myFirstObj = new B();
  • mySecondObj = (A) myFirstObj; <= Failure, because B might implements other methods or properties A doesn't, so impossible to cast
  • mySecondObj = (IPolyline) myFirstObj; <= work, you are limited the cast to the same scope of methods.

Upvotes: 3

Related Questions