C# - How to test at runtime which COM coclass was used to instantiate an interface?

有些话、适合烂在心里 提交于 2019-12-06 11:18:35

问题


Suppose you have a COM interface ICOMInterface that is implemented by coclasses Coclass1 and Coclass2. Neither of these coclasses have interfaces of their own (for simplicity's sake and to illustrate my issue).

In C#, you can create an instance of a COM interface from a coclass like so:

ICOMInterface myComInterface = new Coclass1();

Now, how can you determine whether myComInterface was instantiated by Coclass1 or Coclass2?

Using the "is" statement like follows always returns true, and as such is useless for this purpose.

Debug.WriteLine(myComInterface is Coclass1) // writes "True"
Debug.WriteLine(myComInterface is Coclass2) // writes "True"

This would work if I was testing interfaces, not coclasses, but these coclasses do not have interfaces other than the one they both implement, ICOMInterface.

I am hoping that there is a simple answer to this rather generic scenario that I am overlooking, otherwise I can post more specific details if required.

Thanks for your help!


回答1:


If the COM object implements the IPersist interface, you can get its CLSID through the IPersist::GetClassID() method. This may be all you need to know what class you're working with. You can also get the human-readable ProgID through the WinAPI ProgIDFromCLSID() method.

See here: C# Get progID from COM object



来源:https://stackoverflow.com/questions/3348554/c-sharp-how-to-test-at-runtime-which-com-coclass-was-used-to-instantiate-an-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!