Why does accessing a COM object from .NET, without going through the Interop class, sometimes work?

后端 未结 3 2257
面向向阳花
面向向阳花 2021-02-19 23:06

When you interface a COM object from .NET code, VS creates an interop DLL, with interop classes.

Example:

You have a foo.dll the implements a COM library Foo, th

相关标签:
3条回答
  • 2021-02-19 23:37

    The Bar() constructor in principle should be returning the interface explicitly instead of the class object. I can't quite figure out how .NET is supporting the construction of an interface!?

    In any case, you can click on the Bar() constructor and hit Shift-F12. This will show you anywhere else in the code where that constructor is being used. I can't think of a way to prevent a user from calling this constructor inadvertently.

    0 讨论(0)
  • 2021-02-19 23:41

    Great question. Many people are surprised this works at all because Bar is an interface and surely you shouldn't be able to create a new instance of an interface! But although I can't seem to find any specifics of the implementation, I remember reading in Adam Nathan's COM interop book that C# makes a special exception for COM interfaces marked with a CoClassAttribute and turns the call into an instantiation of the coclass instead.

    But I don't know why it would sometimes work and sometimes not work.

    0 讨论(0)
  • 2021-02-19 23:44

    Have you read the discussion in this question? It discusses exactly this issue I think.

    0 讨论(0)
提交回复
热议问题