0

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

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.